childName cannot be null or empty with camera in Android Studio - java

When I run it, I get an error saying that childName cannot be null. The variable "data" is getting null when taking the photo and I don't know how to fix it.
This is my code.
public class TakePhoto extends AppCompatActivity {
private Button btnPhoto;
private ImageView mImageView;
private static final int CAMERA_REQUEST_CODE = 1;
private StorageReference storage;
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String fecha = df.format(c.getTime());
private ProgressDialog progress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_take_photo);
storage = FirebaseStorage.getInstance().getReference();
btnPhoto = (Button) findViewById(R.id.buttonCamera2);
mImageView = (ImageView) findViewById(R.id.fotoFinal);
progress = new ProgressDialog(this);
btnPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){
Uri uri = data.getData();
StorageReference filepath = storage.child(getIntent().getStringExtra("dato")).child(fecha + " " + uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(TakePhoto.this, "Subiendo...", Toast.LENGTH_LONG).show();
}
});
}
}
}

Related

What is the correct way to handle multiple requestCodes in onActivityResult()?

I have two activities and the second activity should send back a string of text to the appropriate textview on activity 1 depending on if I select button 1 or button 2. I believe my intent in launchFoodActivity() in activity 1 is incorrectly asking for 2 requests at the same time. How can I correct my code to have each string of text be sent to the appropriate textview in activity 1?
Activity 1
public class MainActivity extends AppCompatActivity {
private TextView mReplyTextView1;
private TextView mReplyTextView2;
public static final int TEXT_REQUEST = 1;
public static final int TEXT_REQUEST2 = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mReplyTextView1 = findViewById(R.id.food_text_1);
mReplyTextView2 = findViewById(R.id.food_text_2);
}
public void launchFoodActivity(View view) {
Intent intent = new Intent(this, FoodListActivity.class);
startActivityForResult(intent, TEXT_REQUEST);
Intent intent2 = new Intent(this, FoodListActivity.class);
startActivityForResult(intent2, TEXT_REQUEST2);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
String textFoodReply1 = data.getStringExtra(FoodListActivity.EXTRA_REPLY);
mReplyTextView1.setText(textFoodReply1);
break;
}
}
case 2:
if (requestCode == 2) {
if (resultCode == RESULT_OK) {
String textFoodReply2 = data.getStringExtra(FoodListActivity.EXTRA_REPLY);
mReplyTextView2.setText(textFoodReply2);
break;
}
}
}
}
}
Activity 2
public class FoodListActivity extends AppCompatActivity {
public static final String EXTRA_REPLY = "com.dev20.shoppinglist.extra.REPLY";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_list);
}
public void returnFoodItem1(View view) {
String replyItem1 = getResources().getString(R.string.cheese_text);
Intent replyIntent = new Intent();
replyIntent.putExtra(EXTRA_REPLY, replyItem1);
setResult(RESULT_OK, replyIntent);
finish();
}
public void returnFoodItem2(View view) {
String replyItem2 = getResources().getString(R.string.apples_text);
Intent replyIntent2 = new Intent();
replyIntent2.putExtra(EXTRA_REPLY, replyItem2);
setResult(RESULT_OK, replyIntent2);
finish();
}
}

Android Firebase java.lang.StackOverflowError: stack size 8MB error when user is uploading an image

Hello I'm trying to create a profile screen where the user can upload their own profile image and change the ImageView into something that they've uploaded. But upon using this Upload profile image for a user Firebase as a reference I encountered an error when I'm starting to upload the images to the database.
My Code
public class userMain extends Fragment {
private TextView userfirstName,usersecondName,userNumber,userGender,userEmail,userDate;
private Button btnChoose, btnUpload;
private ImageView imageView;
private Uri filePath;
private FirebaseStorage storage;
private StorageReference storageReference;
private final int PICK_IMAGE_REQUEST = 71;
public userMain() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_user_main, container, false);
btnUpload = (Button) view.findViewById(R.id.savePhoto);
imageView = (ImageView) view.findViewById(R.id.imageView3);
userfirstName = (TextView) view.findViewById(R.id.firstnametv);
usersecondName = (TextView) view.findViewById(R.id.secondnametv);
userNumber = (TextView) view.findViewById(R.id.numbertv);
userGender = (TextView) view.findViewById(R.id.gendertv);
userEmail = (TextView) view.findViewById(R.id.emailtv);
userDate = (TextView) view.findViewById(R.id.datetv);
FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
String useruid=user.getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Accounts").child("Users").child(useruid);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chooseImage();
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadImage();
}
});
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String firstname = dataSnapshot.child("first").getValue(String.class);
String secondname = dataSnapshot.child("second").getValue(String.class);
String number = dataSnapshot.child("number").getValue(String.class);
String gender = dataSnapshot.child("gender").getValue(String.class);
String email = dataSnapshot.child("email").getValue(String.class);
String date = dataSnapshot.child("date").getValue(String.class);
userfirstName.setText(firstname);
usersecondName.setText(secondname);
userNumber.setText(number);
userGender.setText(gender);
userEmail.setText(email);
userDate.setText(date);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return view;
}
private void uploadImage() {
if(filePath != null)
{
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(getContext(), "Uploaded", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getContext(), "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
}
}
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
String useruid=user.getUid();
final DatabaseReference img = FirebaseDatabase.getInstance().getReference().child("Accounts").child("Users").child(useruid);
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null )
{
filePath = data.getData();
StorageReference filepath= storageReference.child("Images").child(filePath.getLastPathSegment());
filepath.putFile(filePath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
img.child("image").setValue(downloadUrl);
}
});
}
}
}
Change this:
StorageReference filepath= storageReference.child("Images").child(filePath.getLastPathSegment());
filepath.putFile(filePath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
img.child("image").setValue(downloadUrl);
}
to this:
StorageReference filepath= storageReference.child("Images").child(filePath.getLastPathSegment());
filepath.putFile(filePath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String downloadUrl = taskSnapshot.getDownloadUrl().toString()
img.child("image").setValue(downloadUrl);
}
saving the downloadUrl as string in your firebase database

Recorded video won't show on viewVideo

I just need help on my codes, I'm using Android Studio. Everything is working fine but the recorded video won't show in viewVideo on my layout.
Here's the code:
public class MainActivity extends AppCompatActivity {
static final int REQUEST_VIDEO_CAPTURE = 1;
VideoView resultvideo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button click = (Button)findViewById(R.id.videorec);
resultvideo = (VideoView)findViewById(R.id.videoView);
}
public void dispatchTakeVideoIntent(View v) {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_VIDEO_CAPTURE && resultCode == RESULT_OK) {
Uri videoUri = data.getData();
resultvideo.setVideoURI(videoUri);
}
}
}
Uri videoUri = data.getData();
resultvideo.setVideoURI(videoUri);
// start call missing
resultvideo.start();

Why I'm not receiving any results from onActivityResult

I'm starting DialogFragment from AddFragment by calling showPickImageDialog() method on button press. And in AlertDialogFragment onActivityResult I'm sending results back to AddFragment but AddFragment is not receiving any results. Any ideas why?
AddFragment:
public class AddFragment extends Fragment {
private static final int REQUEST_IMAGE = 3;
private static final String DIALOG_IMAGE = "image";
private static final String TAG = "TAG";
void showPickImageDialog() {
FragmentManager fm = getActivity()
.getSupportFragmentManager();
AlertDialogFragment pdialog = new AlertDialogFragment();
pdialog.setTargetFragment(this, REQUEST_IMAGE);
pdialog.show(fm, DIALOG_IMAGE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK){
Log.e(TAG,"back in AddFragment");
}
}
}
In AlertDialogFragment Im calling sendResult method from onActivityResult method. SendResult method is called I checked it with Logs
AlertDialogFragment:
public class AlertDialogFragment extends DialogFragment {
private final static String TAG = "Cload";
public static final String EXTRA_PHOTOFILENAME =
"com.example.tadas.dreamcload1.image";
private static final int REQUEST_IMAGE = 3;
private String filename;
private Uri uri;
private void sendResult(int resultCode) {
if(getTargetFragment() == null){return;}
Intent i = new Intent();
i.putExtra(EXTRA_PHOTOFILENAME,filename);
getTargetFragment()
.onActivityResult(getTargetRequestCode(), resultCode, i);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//LayoutInflater inflater = getLayoutInflater();
// View dialogLaout = inflater.inflate(R.layout.custom_dialog_pick_image,null);
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.custom_dialog_pick_image, null);
final AlertDialog dialog = new AlertDialog.Builder(getActivity())
.setView(view)
.create();
ImageButton gallerybtn = (ImageButton)view.findViewById(R.id.gallery);
ImageButton camerabtn = (ImageButton)view.findViewById(R.id.camera);
gallerybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e(TAG,"gallery btn pressed");
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_IMAGE);
}
});
camerabtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return dialog;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK){
uri = data.getData();
final String[] filePathColumn = {MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DISPLAY_NAME};
Cursor c = getActivity().getContentResolver()
.query(uri,filePathColumn,null,null,null);
if (c.moveToFirst()){
int ids = c.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
uri = Uri.parse(c.getString(ids));
filename = uri.toString();
c.close();
}
sendResult(Activity.RESULT_OK);
dismiss();
}
}
You can override your onActivityResult method in your Activity and call your Fragment's onActivityResult manually like below:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.your_container);
fragment.onActivityResult(requestCode, resultCode, data);
}
You can define this part in your Activity's onActivityResult method:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK){
uri = data.getData();
final String[] filePathColumn = {MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DISPLAY_NAME};
Cursor c = getActivity().getContentResolver()
.query(uri,filePathColumn,null,null,null);
if (c.moveToFirst()){
int ids = c.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
uri = Uri.parse(c.getString(ids));
filename = uri.toString();
c.close();
}
// You do not need this any more
//sendResult(Activity.RESULT_OK);
//dismiss();
// Just find your fragment and call it's onActivityResult
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.your_container);
fragment.onActivityResult(requestCode, resultCode, data);
}
}
I think this change'll help you.

Multiple startActivityForResult()

I need to call this function twice in my application pointing to two different activities. I have a unique request code for each call, however my app seems to crash everytime it launches the second activity.
Here is my code (only relevant parts):
MainActivity:
//Request Info vars
static final int GET_DETAILS = 1;
static final int EDIT_DETAILS = 2;
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
public void onMapClick(LatLng latLng) {
lat = latLng.latitude;
lon = latLng.longitude;
startActivityForResult(new Intent(MapsActivity.this,NewMarkerActivity.class), GET_DETAILS);
}
});
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
current_marker = marker;
startActivityForResult(new Intent(MapsActivity.this,EditMarkerActivity.class), EDIT_DETAILS);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == GET_DETAILS) {
if (resultCode == RESULT_OK) {
String marker_title=data.getStringExtra("title");
String marker_snippet = data.getStringExtra("snippet");
addMarker(lat, lon, marker_title, marker_snippet);
mMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(lat, lon)));
}
} if (requestCode == EDIT_DETAILS) {
if (resultCode == RESULT_OK) {
String marker_title=data.getStringExtra("title");
String marker_snippet = data.getStringExtra("snippet");
current_marker.setTitle(marker_title);
current_marker.setSnippet(marker_snippet);
}
}
}
EditMarkerActivity:
public class EditMarkerActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_marker_activity);
Button save_btn = (Button)findViewById(R.id.btn_save);
save_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText editName = (EditText)findViewById(R.id.editName);
String marker_title = editName.getText().toString();
EditText editSnippet = (EditText)findViewById(R.id.editSnippet);
String marker_snippet = editSnippet.getText().toString();
Intent _result = new Intent();
_result.putExtra("title", marker_title);
_result.putExtra("snippet", marker_snippet);
setResult(Activity.RESULT_OK, _result);
finish();
}
});
}
}
NewMarkerActivity:
public class NewMarkerActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_marker_activity);
Button save_btn = (Button)findViewById(R.id.btn_save);
save_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText editName = (EditText)findViewById(R.id.editName);
String marker_title = editName.getText().toString();
EditText editSnippet = (EditText)findViewById(R.id.editSnippet);
String marker_snippet = editSnippet.getText().toString();
Intent _result = new Intent();
_result.putExtra("title", marker_title);
_result.putExtra("snippet", marker_snippet);
setResult(Activity.RESULT_OK, _result);
finish();
}
});
}
}
Any obvious issues? Help or insight to this problem will be greatly appreciated :)
Here is my output from Logcat:
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.geekybrackets.virtualtourguide/com.geekybrackets.virtualtourguide.EditMarkerActivity}; have you declared this activity in your AndroidManifest.xml?
Turns out the issue was that I hadn't defined the activity in the manifest file.
Dear old me, now i know to check my errors !
Thanks again guys, case closed.

Categories