Committed files for others to look at and improve: Photo upload does not work properly.

This commit is contained in:
Niels Zwemmer
2017-06-24 13:40:02 +02:00
parent 83d2bda5c1
commit 5181128504
4 changed files with 178 additions and 28 deletions

View File

@@ -3,6 +3,9 @@
package="nl.myhyvesbookplus.tagram"> package="nl.myhyvesbookplus.tagram">
<uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application <application
android:allowBackup="true" android:allowBackup="true"

View File

@@ -18,7 +18,7 @@ import com.google.firebase.auth.FirebaseAuth;
import nl.myhyvesbookplus.tagram.controller.UploadClass; import nl.myhyvesbookplus.tagram.controller.UploadClass;
import nl.myhyvesbookplus.tagram.model.BitmapPost; import nl.myhyvesbookplus.tagram.model.BitmapPost;
public class MainActivity extends AppCompatActivity implements CameraFragment.OnFragmentInteractionListener, TimelineFragment.OnFragmentInteractionListener, UploadClass.ProfilePictureUpdatedListener { public class MainActivity extends AppCompatActivity implements CameraFragment.OnFragmentInteractionListener, ProfileFragment.OnFragmentInteractionListener, TimelineFragment.OnFragmentInteractionListener, UploadClass.ProfilePictureUpdatedListener {
final static private String TAG = "MainScreen"; final static private String TAG = "MainScreen";
FirebaseAuth mAuth; FirebaseAuth mAuth;
@@ -110,6 +110,7 @@ public class MainActivity extends AppCompatActivity implements CameraFragment.On
@Override @Override
public void ProfilePictureUpdated(Boolean success) { public void ProfilePictureUpdated(Boolean success) {
Log.d(TAG, "ProfilePictureUpdated: Ja ik luister naar je!");
FragmentManager man = getFragmentManager(); FragmentManager man = getFragmentManager();
ProfileFragment frag = (ProfileFragment) man.findFragmentById(R.id.content); ProfileFragment frag = (ProfileFragment) man.findFragmentById(R.id.content);
FragmentTransaction transaction = man.beginTransaction(); FragmentTransaction transaction = man.beginTransaction();
@@ -117,6 +118,7 @@ public class MainActivity extends AppCompatActivity implements CameraFragment.On
transaction.detach(frag) transaction.detach(frag)
.attach(frag) .attach(frag)
.commit(); .commit();
Log.d(TAG, "ProfilePictureUpdated: Done reloading fragment");
} }
} }

View File

@@ -1,14 +1,19 @@
package nl.myhyvesbookplus.tagram; package nl.myhyvesbookplus.tagram;
import android.app.Activity;
import android.app.Fragment; import android.app.Fragment;
import android.app.ProgressDialog; import android.app.ProgressDialog;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri; import android.net.Uri;
import android.os.Bundle; import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore; import android.provider.MediaStore;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
@@ -17,7 +22,6 @@ import android.widget.ImageButton;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import com.bumptech.glide.Glide; import com.bumptech.glide.Glide;
import com.firebase.ui.storage.images.FirebaseImageLoader; import com.firebase.ui.storage.images.FirebaseImageLoader;
import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnCompleteListener;
@@ -27,32 +31,83 @@ import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.StorageReference;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import nl.myhyvesbookplus.tagram.controller.UploadClass; import nl.myhyvesbookplus.tagram.controller.UploadClass;
import static android.app.Activity.RESULT_OK; import static android.app.Activity.RESULT_OK;
import static java.lang.System.currentTimeMillis;
/** /**
* A simple {@link Fragment} subclass. * A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link ProfileFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link ProfileFragment#newInstance} factory method to
* create an instance of this fragment.
*/ */
public class ProfileFragment extends Fragment implements View.OnClickListener { public class ProfileFragment extends Fragment implements View.OnClickListener {
static final int REQUEST_IMAGE_CAPTURE = 1; // static final int REQUEST_IMAGE_CAPTURE = 1;
static final int REQUEST_TAKE_PHOTO = 1;
final static private String TAG = "ProfileFragment";
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private static Uri downloadUrl;
protected Button changePwdButton; protected Button changePwdButton;
protected ImageButton profilePicButton; protected ImageButton profilePicButton;
/// Views ///
protected StorageReference httpsReference; protected StorageReference httpsReference;
protected TextView profileName; protected TextView profileName;
protected ImageView profilePicture; protected ImageView profilePicture;
protected FirebaseUser user; protected FirebaseUser user;
ProgressDialog progressDialog;
ProgressDialog progressDialog;
String mCurrentPhotoPath;
File photoFile = null;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
/// Required empty public constructor /// /// Required empty public constructor ///
public ProfileFragment() { public ProfileFragment() {}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ProfileFragment.
*/
// TODO: Rename and change types and number of parameters
public static ProfileFragment newInstance(String param1, String param2) {
ProfileFragment fragment = new ProfileFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
} }
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
user = FirebaseAuth.getInstance().getCurrentUser(); user = FirebaseAuth.getInstance().getCurrentUser();
} }
@@ -89,7 +144,7 @@ public class ProfileFragment extends Fragment implements View.OnClickListener {
Glide.with(this).using(new FirebaseImageLoader()).load(httpsReference).into(profilePicture); Glide.with(this).using(new FirebaseImageLoader()).load(httpsReference).into(profilePicture);
} }
profilePicture.invalidate(); // To display the profile picture after it has been updated. profilePicture.invalidate();
if (user != null && user.getDisplayName() != null) { if (user != null && user.getDisplayName() != null) {
profileName.setText(user.getDisplayName()); profileName.setText(user.getDisplayName());
@@ -98,6 +153,13 @@ public class ProfileFragment extends Fragment implements View.OnClickListener {
return view; return view;
} }
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
/** /**
* Called when a view has been clicked. * Called when a view has been clicked.
* *
@@ -116,45 +178,78 @@ public class ProfileFragment extends Fragment implements View.OnClickListener {
} }
// TODO Make the function actually do something. // TODO Make the function actually do something.
/** /**
* Performs profile picture change action. * Performs profile picture change action.
*/ */
public void profilePicOnClick() { public void profilePicOnClick() {
// Log.d(TAG, "profilePicOnClick: JE KAN NOG GEEN FOTO UPLOADEN");
dispatchTakePictureIntent(); dispatchTakePictureIntent();
} }
/** /**
* Starts new intent for access to the built-in camera of device. * Starts new intent for access to the built-in camera of device.
*/ */
// private void dispatchTakePictureIntent() {
// Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
// startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
// }
// }
private void dispatchTakePictureIntent() { private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) { if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); // Create the File where the photo should go
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
// Uri uri = Uri.fromFile(photoFile); //TODO Als je dit in takePictureIntent zet ipv photoFile, grote boos.
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoFile);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
} }
} }
/** /**
* Grabs the image just taken by the built-in camera and pushes this image to the user account. * Grabs the image just taken by the built-in camera and pushes this image to the user account.
*
* @param requestCode * @param requestCode
* @param resultCode * @param resultCode
* @param data * @param data
*/ */
@Override @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
Bundle extras = data.getExtras(); Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data"); progressDialog = ProgressDialog.show(getActivity(), getString(R.string.please_wait), "bezig met uploaden", false, false);
progressDialog = ProgressDialog.show(getActivity(), getString(R.string.please_wait), "Uploading...", true, false);
UploadClass uploadClass = new UploadClass(getActivity()); UploadClass uploadClass = new UploadClass(getActivity());
uploadClass.uploadProfilePicture(imageBitmap); uploadClass.uploadProfilePicture(photoFile);
progressDialog.dismiss();
} }
} }
private File createImageFile() throws IOException {
// Create an image file name
String imageFileName = "JPEG_" + currentTimeMillis();
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
// TODO Make this function into its own class for modularity. // TODO Make this function into its own class for modularity.
/** /**
* Performs password reset action. * Performs password reset action.
*/ */
@@ -165,8 +260,8 @@ public class ProfileFragment extends Fragment implements View.OnClickListener {
@Override @Override
public void onComplete(@NonNull Task<Void> task) { public void onComplete(@NonNull Task<Void> task) {
Toast.makeText(getActivity(), task.isSuccessful() Toast.makeText(getActivity(), task.isSuccessful()
? getString(R.string.mail_successful) ? "An e-mail was sent, please follow its instructions."
: getString(R.string.mail_failed), : "An error occurred, please check internet connection.",
Toast.LENGTH_SHORT).show(); Toast.LENGTH_SHORT).show();
} }
}); });
@@ -174,4 +269,43 @@ public class ProfileFragment extends Fragment implements View.OnClickListener {
// TODO Add code here for when there is no currently active user. // TODO Add code here for when there is no currently active user.
} }
} }
/**
* Obligatory onAttach function included in fragments.
* @param context provided context for the function to operate on.
*/
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
/**
* Obligatory onDetach function included in fragments.
*/
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* See the Android Training lesson http://developer.android.com/training/basics/fragments/communicating.html
* for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
} }

View File

@@ -6,6 +6,7 @@ import android.net.Uri;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.util.Log; import android.util.Log;
import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.OnSuccessListener;
@@ -20,6 +21,9 @@ import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask; import com.google.firebase.storage.UploadTask;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import nl.myhyvesbookplus.tagram.model.BitmapPost; import nl.myhyvesbookplus.tagram.model.BitmapPost;
import nl.myhyvesbookplus.tagram.model.UriPost; import nl.myhyvesbookplus.tagram.model.UriPost;
@@ -100,10 +104,14 @@ public class UploadClass {
/// Profile picture /// /// Profile picture ///
public void uploadProfilePicture(Bitmap picture) { public void uploadProfilePicture(File picture) {
byte[] uploadPhoto = bitmapToBytes(picture); try {
FileInputStream stream = new FileInputStream(picture);
// Uri uri = Uri.fromFile(picture);
Log.d(TAG, "uploadProfilePicture: This is the uri:" + stream.toString());
oldPicture = mUser.getPhotoUrl(); oldPicture = mUser.getPhotoUrl();
UploadTask photoUpload = mStorageRef.child("profile").child(getUserUid() + "_" + currentTimeMillis()).putBytes(uploadPhoto);
UploadTask photoUpload = mStorageRef.child("profile").child(getUserUid() + "_" + currentTimeMillis()).putStream(stream);
photoUpload.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { photoUpload.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override @Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
@@ -111,6 +119,9 @@ public class UploadClass {
updateProfilePictureInUser(downloadUrl); updateProfilePictureInUser(downloadUrl);
} }
}); });
} catch (FileNotFoundException fnfe) {
Log.d(TAG, "uploadProfilePicture: FIle niet gevonden");
}
} }
private void updateProfilePictureInUser(Uri url) { private void updateProfilePictureInUser(Uri url) {