[Android General] prashantmoroliya:
I made Instagram type application in Android Studio, but whenever I try to upload image in my app, it uploads to my profile picture. I checked my intents and they are really perfect. First file is GalleryFragment.java in which we will select the photo which we want to upload and Second file is NextActivity.java which is used to Share the image to profile. But in GalleryFragment.java I have intent getActivity() to NextActivity.java and AccountSettingsActivity.java in which we can change out profile picture. But whenever I click on Next it doesn't take me to NextActivity.java but to the AccountSettingsActivity.java and updates my profile picture. If there is Firebase error so tell me. And the same issue is occurred when I try to upload photo from camera inside the application and it doesn't do anything. I have posted 3 files.

GalleryFragment.java

package darthvader.com.pictagram.Share;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.util.ArrayList;
import java.util.Objects;

import darthvader.com.pictagram.Profile.AccountSettingsActivity;
import darthvader.com.pictagram.R;
import darthvader.com.pictagram.Utils.FilePaths;
import darthvader.com.pictagram.Utils.FileSearch;
import darthvader.com.pictagram.Utils.GridImageAdapter;

public class GalleryFragment extends Fragment {
private static final String TAG = "GalleryFragment";

//constants
private static final int NUM_GRID_COLUMNS = 3;

//widgets
private GridView gridView;
private ImageView galleryImage;
private ProgressBar mProgressBar;
private Spinner directorySpinner;

//vars
private ArrayList<String> directories;
private String mAppend = "file:/";
private String mSelectedImage;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
galleryImage = view.findViewById(R.id.galleryImageView);
gridView = view.findViewById(R.id.gridView);
directorySpinner = view.findViewById(R.id.spinnerDirectory);
mProgressBar = view.findViewById(R.id.progressBar);
mProgressBar.setVisibility(View.GONE);
directories = new ArrayList<>();
Log.d(TAG, "onCreateView: started.");

ImageView shareClose = view.findViewById(R.id.ivCloseShare);
shareClose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: closing the gallery fragment.");
Objects.requireNonNull(getActivity()).finish();
}
});

TextView nextScreen = view.findViewById(R.id.tvNext);
nextScreen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to the final share screen.");

if(isRootTask()){
Intent intent = new Intent(getActivity(), NextActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
startActivity(intent);
}else{
Intent intent = new Intent(getActivity(), AccountSettingsActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
intent.putExtra(getString(R.string.return_to_fragment), getString(R.string.edit_profile_fragment));
startActivity(intent);
getActivity().finish();
}

}
});

init();

return view;
}

private boolean isRootTask(){
return ((ShareActivity) getActivity()).getTask() == 0;
}

private void init(){
FilePaths filePaths = new FilePaths();

//check for other folders indide "/storage/emulated/0/pictures"
if (FileSearch.getDirectoryPaths(filePaths.PICTURES) != null) {
directories = FileSearch.getDirectoryPaths(filePaths.PICTURES);
}
directories.add(filePaths.CAMERA);

ArrayList<String> directoryNames = new ArrayList<>();
for (int i = 0; i < directories.size(); i++) {
Log.d(TAG, "init: directory: " + directories.get(i));
int index = directories.get(i).lastIndexOf("/");
String string = directories.get(i).substring(index);
directoryNames.add(string);
}

ArrayAdapter<String> adapter = new ArrayAdapter<>(Objects.requireNonNull(getActivity()),
android.R.layout.simple_spinner_item, directoryNames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
directorySpinner.setAdapter(adapter);

directorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: selected: " + directories.get(position));

//setup our image grid for the directory chosen
setupGridView(directories.get(position));
}

@Override
public void onNothingSelected(AdapterView<?> parent) {

}
});
}

private void setupGridView(String selectedDirectory){
Log.d(TAG, "setupGridView: directory chosen: " + selectedDirectory);
final ArrayList<String> imgURLs = FileSearch.getFilePaths(selectedDirectory);

//set the grid column width
int gridWidth = getResources().getDisplayMetrics().widthPixels;
int imageWidth = gridWidth/NUM_GRID_COLUMNS;
gridView.setColumnWidth(imageWidth);

//use the grid adapter to adapter the images to gridview
GridImageAdapter adapter = new GridImageAdapter(getActivity(), R.layout.layout_grid_imageview, mAppend, imgURLs);
gridView.setAdapter(adapter);

//set the first image to be displayed when the activity fragment view is inflated
try{
setImage(imgURLs.get(0), galleryImage, mAppend);
mSelectedImage = imgURLs.get(0);
}catch (ArrayIndexOutOfBoundsException e){
Log.e(TAG, "setupGridView: ArrayIndexOutOfBoundsException: " +e.getMessage() );
}

gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: selected an image: " + imgURLs.get(position));

setImage(imgURLs.get(position), galleryImage, mAppend);
mSelectedImage = imgURLs.get(position);
}
});

}

private void setImage(String imgURL, ImageView image, String append){
Log.d(TAG, "setImage: setting image");

ImageLoader imageLoader = ImageLoader.getInstance();

imageLoader.displayImage(append + imgURL, image, new ImageLoadingListener() {
@Override
public void onLoadingStarted(String imageUri, View view) {
mProgressBar.setVisibility(View.VISIBLE);
}

@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
mProgressBar.setVisibility(View.INVISIBLE);
}

@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
mProgressBar.setVisibility(View.INVISIBLE);
}

@Override
public void onLoadingCancelled(String imageUri, View view) {
mProgressBar.setVisibility(View.INVISIBLE);
}
});
}
}

NextActivity.java

package darthvader.com.pictagram.Share;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

import darthvader.com.pictagram.R;
import darthvader.com.pictagram.Utils.FirebaseMethods;
import darthvader.com.pictagram.Utils.UniversalImageLoader;
import darthvader.com.pictagram.models.User;

public class NextActivity extends AppCompatActivity {

private static final String TAG = "NextActivity";

//firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private FirebaseMethods mFirebaseMethods;

//widgets
private EditText mCaption;

//vars
private String mAppend = "file:/";
private int imageCount = 0;
private String imgUrl;
private Bitmap bitmap;
private Intent intent;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
mFirebaseMethods = new FirebaseMethods(NextActivity.this);
mCaption = findViewById(R.id.caption);

setupFirebaseAuth();

ImageView backArrow = findViewById(R.id.ivBackArrow);
backArrow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: closing the activity");
finish();
}
});

TextView share = findViewById(R.id.tvShare);
share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to the final share screen.");
//upload the image to firebase
Toast.makeText(NextActivity.this, "Attempting to upload new photo", Toast.LENGTH_SHORT).show();
String caption = mCaption.getText().toString();

if(intent.hasExtra(getString(R.string.selected_image))){
imgUrl = intent.getStringExtra(getString(R.string.selected_image));
mFirebaseMethods.uploadNewPhoto(getString(R.string.new_photo), caption, imageCount, imgUrl,null);
}
else if(intent.hasExtra(getString(R.string.selected_bitmap))){
bitmap = intent.getParcelableExtra(getString(R.string.selected_bitmap));
mFirebaseMethods.uploadNewPhoto(getString(R.string.new_photo), caption, imageCount, null,bitmap);
}

}
});

setImage();
}

private void someMethod(){
/*
Step 1)
Create a data model for Photos

Step 2)
Add properties to the Photo Objects (caption, date, imageUrl, photo_id, tags, user_id)

Step 3)
Count the number of photos that the user already has.

Step 4)
a) Upload the photo to Firebase Storage
b) insert into 'photos' node
c) insert into 'user_photos' node

*/

}

/**
* gets the image url from the incoming intent and displays the chosen image
*/
private void setImage(){
intent = getIntent();
ImageView image = findViewById(R.id.imageShare);

if(intent.hasExtra(getString(R.string.selected_image))){
imgUrl = intent.getStringExtra(getString(R.string.selected_image));
Log.d(TAG, "setImage: got new image url: " + imgUrl);
UniversalImageLoader.setImage(imgUrl, image, null, mAppend);
}
else if(intent.hasExtra(getString(R.string.selected_bitmap))){
bitmap = intent.getParcelableExtra(getString(R.string.selected_bitmap));
Log.d(TAG, "setImage: got new bitmap");
image.setImageBitmap(bitmap);
}
}

/*
------------------------------------ Firebase ---------------------------------------------
*/

/**
* Setup the firebase auth object
*/
private void setupFirebaseAuth(){
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
Log.d(TAG, "onDataChange: image count: " + imageCount);

mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();

if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};

myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {

imageCount = mFirebaseMethods.getImageCount(dataSnapshot);
Log.d(TAG, "onDataChange: image count: " + imageCount);

}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});
}

@Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}

@Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}

PhotoFragment.java

package darthvader.com.pictagram.Share;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import java.util.Objects;

import darthvader.com.pictagram.Profile.AccountSettingsActivity;
import darthvader.com.pictagram.R;
import darthvader.com.pictagram.Utils.Permissions;

public class PhotoFragment extends Fragment {
private static final String TAG = "PhotoFragment";

//constant
private static final int PHOTO_FRAGMENT_NUM = 1;
private static final int GALLERY_FRAGMENT_NUM = 2;
private static final int CAMERA_REQUEST_CODE = 5;

@Nullable
@Override
public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_photo, container, false);
Log.d(TAG, "onCreateView: started.");

Button btnLaunchCamera = (Button) view.findViewById(R.id.btnLaunchCamera);
btnLaunchCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: launching camera.");

if(((ShareActivity)getActivity()).getCurrentTabNumber() == PHOTO_FRAGMENT_NUM){
if(((ShareActivity)getActivity()).checkPermissions(Permissions.CAMERA_PERMISSION[0])){
Log.d(TAG, "onClick: starting camera");
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
}else{
Intent intent = new Intent(getActivity(), ShareActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
}
});

return view;
}

private boolean isRootTask(){
if(((ShareActivity)getActivity()).getTask() == 0){
return true;
}
else{
return false;
}
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if(requestCode == CAMERA_REQUEST_CODE){
Log.d(TAG, "onActivityResult: done taking a photo.");
Log.d(TAG, "onActivityResult: attempting to navigate to final share screen.");

Bitmap bitmap;
bitmap = (Bitmap) Objects.requireNonNull(data.getExtras()).get("data");

if(isRootTask()){
try{
Log.d(TAG, "onActivityResult: received new bitmap from camera: " + bitmap);
Intent intent = new Intent(getActivity(), NextActivity.class);
intent.putExtra(getString(R.string.selected_bitmap), bitmap);
startActivity(intent);
}catch (NullPointerException e){
Log.d(TAG, "onActivityResult: NullPointerException: " + e.getMessage());
}
}else{
try{
Log.d(TAG, "onActivityResult: received new bitmap from camera: " + bitmap);
Intent intent = new Intent(getActivity(), AccountSettingsActivity.class);
intent.putExtra(getString(R.string.selected_bitmap), bitmap);
intent.putExtra(getString(R.string.return_to_fragment), getString(R.string.edit_profile_fragment));
startActivity(intent);
getActivity().finish();
}catch (NullPointerException e){
Log.d(TAG, "onActivityResult: NullPointerException: " + e.getMessage());
}
}

}
}
}