Not able to display image in fragment - android

I am not able to display an image inside the imageview in fragment.
I have grant all the permission of storage.
Code executes without any error but doesn't display an image.
Am i doing anything wrong please help.
i have display whole code here.
public class PrescriptionUploadFragment extends Fragment implements View.OnClickListener {
private static final int REQUEST_PERMISSION_CODE = 111;
private static final int PICK_IMAGE_REQUEST = 1;
private ExtendedFloatingActionButton eFabUpload, eFabChooseFile;
private EditText etDescriptionUpload;
private ImageView imgPrescriptionUploads;
private ProgressBar pbPrescriptionUpload;
private ChangeFragment changeFragment;
private InternetCheck internetCheck;
private FirebaseAuth mAuth;
private FirebaseUser mUser;
private DatabaseReference mDatabaseReference;
private StorageReference mStorageReference, ref;
private String UserID = "";
private Uri mImageUri;
private String id;
public PrescriptionUploadFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
UserID = mUser.getUid();
mDatabaseReference = FirebaseDatabase.getInstance().getReference("Prescription").child(UserID);
mStorageReference = FirebaseStorage.getInstance().getReference("Prescription").child(UserID);
internetCheck = new InternetCheck(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_prescription_upload, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
InitializeViews(view);
}
private void InitializeViews(View view) {
eFabUpload = (ExtendedFloatingActionButton) view.findViewById(R.id.fabUploadPrescription);
eFabUpload.setOnClickListener(this);
eFabChooseFile = (ExtendedFloatingActionButton) view.findViewById(R.id.fabChooseFile);
eFabChooseFile.setOnClickListener(this);
etDescriptionUpload = (EditText) view.findViewById(R.id.etDescriptionUplaod);
pbPrescriptionUpload = (ProgressBar) view.findViewById(R.id.pbPrescriptionUpload);
imgPrescriptionUploads = (ImageView) view.findViewById(R.id.imgPrescriptionUploads);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
changeFragment = (ChangeFragment) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement MyInterface");
}
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.fabChooseFile:
onClickChooseFile();
break;
case R.id.fabUploadPrescription:
onClickUploadPrescription();
break;
}
}
private void onClickChooseFile() {
if (CheckingPermissionIsEnabled()) {
Intent intentCamera = new Intent();
intentCamera.setType("image/*");
intentCamera.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intentCamera, PICK_IMAGE_REQUEST);
} else {
RequestMultiplePermission();
}
}
private void onClickUploadPrescription() {
if (mImageUri != null && internetCheck.checkConnection()){
id = mDatabaseReference.push().getKey();
ref = mStorageReference.child(id).child(System.currentTimeMillis() +"." + getExtension(mImageUri) );
ref.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
PrescriptionUpload prescriptionUpload = new PrescriptionUpload(id ,mImageUri ,
etDescriptionUpload.getText().toString().trim());
mDatabaseReference.child(id).setValue(prescriptionUpload).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
changeFragment.changeFrag("PRESCRIPTION_MAIN_FRAGMENT");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
pbPrescriptionUpload.setProgress((int) progress);
}
});
} else {
Toast.makeText(getActivity(), "Not an Image !", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
mImageUri = data.getData();
if (mImageUri != null){
imgPrescriptionUploads.setImageURI(mImageUri);
} else {
Toast.makeText(getActivity(), "Image not selected !", Toast.LENGTH_SHORT).show();
}
}
}
private String getExtension(Uri uri) {
ContentResolver cr = getActivity().getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cr.getType(uri));
}
public boolean CheckingPermissionIsEnabled() {
int FirstPermissionResult = ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), INTERNET);
int FifthPermissionResult = ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), ACCESS_WIFI_STATE);
int EighthPermissionResult = ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), READ_EXTERNAL_STORAGE);
int NinthPermissionResult = ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), WRITE_EXTERNAL_STORAGE);
return FirstPermissionResult == PackageManager.PERMISSION_GRANTED &&
FifthPermissionResult == PackageManager.PERMISSION_GRANTED &&
EighthPermissionResult == PackageManager.PERMISSION_GRANTED &&
NinthPermissionResult == PackageManager.PERMISSION_GRANTED;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSION_CODE:
if (grantResults.length > 0) {
boolean INTERNET = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean ACCESS_WIFI_STATE = grantResults[1] == PackageManager.PERMISSION_GRANTED;
boolean READ_EXTERNAL_STORAGE = grantResults[2] == PackageManager.PERMISSION_GRANTED;
boolean WRITE_EXTERNAL_STORAGE = grantResults[3] == PackageManager.PERMISSION_GRANTED;
if (INTERNET && ACCESS_WIFI_STATE && READ_EXTERNAL_STORAGE && WRITE_EXTERNAL_STORAGE) {
Toast.makeText(getActivity(), "Permission Granted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "Permission Denied", Toast.LENGTH_LONG).show();
}
}
break;
}
}
private void RequestMultiplePermission() {
// Creating String Array with Permissions.
ActivityCompat.requestPermissions(getActivity(), new String[]
{
INTERNET,
ACCESS_WIFI_STATE,
READ_EXTERNAL_STORAGE,
WRITE_EXTERNAL_STORAGE
}, REQUEST_PERMISSION_CODE);
}
}
and xml code
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:theme="#style/Theme.MaterialComponents"
tools:context=".PrescriptionUploadFragment">
<ImageView
android:id="#+id/imgPrescriptionUploads"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="24dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="24dp"
android:layout_marginBottom="24dp"
android:scaleType="centerCrop"
app:layout_constraintBottom_toTopOf="#+id/DescriptionUpload"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/DescriptionUpload"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginEnd="24dp"
android:layout_marginBottom="16dp"
android:gravity="center"
app:layout_constraintBottom_toTopOf="#+id/pbPrescriptionUpload"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<EditText
android:id="#+id/etDescriptionUplaod"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/et_description" />
</com.google.android.material.textfield.TextInputLayout>
<ProgressBar
android:id="#+id/pbPrescriptionUpload"
style="#style/Widget.MaterialProgressBar.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginEnd="24dp"
android:layout_marginBottom="16dp"
android:indeterminate="true"
app:layout_constraintBottom_toTopOf="#+id/linearLayout3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<LinearLayout
android:id="#+id/linearLayout3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginEnd="24dp"
android:layout_marginBottom="16dp"
android:gravity="center"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
android:id="#+id/fabChooseFile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_marginEnd="20dp"
android:background="#color/colorPrimaryDark"
android:backgroundTint="#color/colorPrimaryDark"
android:shadowColor="#color/colorPrimary"
android:text="#string/fabChooseFile"
android:textAlignment="center"
android:textColor="#color/colorText"
android:textColorLink="#color/colorPrimaryDark"
app:rippleColor="#color/colorText"
app:tint="#color/colorPrimaryDark" />
<com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
android:id="#+id/fabUploadPrescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:background="#color/colorPrimaryDark"
android:backgroundTint="#color/colorPrimaryDark"
android:shadowColor="#color/colorPrimary"
android:text="#string/fabUpload"
android:textAlignment="center"
android:textColor="#color/colorText"
android:textColorLink="#color/colorPrimaryDark"
app:rippleColor="#color/colorText"
app:tint="#color/colorPrimaryDark" />
</LinearLayout>
enter code here

Related

How to upload two(2) image with caption to firebase database?

Hi guys I'm trying to upload 2(two) images on firebase with captions but it only uploads the first successfully then the field for 2nd image box (nimagetrail2) copies the bitmap on the 1st image box (nimagetrial) on the database. Can someone help me fix this so that each image gets its own bitmap?
XML file
<ImageView
android:id="#+id/imagetrial"
android:layout_width="85dp"
android:layout_height="85dp"
android:layout_marginTop="32dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/id" />
<ImageView
android:id="#+id/imagetrail2"
android:layout_width="85dp"
android:layout_height="85dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imagetrial"
app:srcCompat="#drawable/payment_l" />
<EditText
android:id="#+id/editcap"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintEnd_toEndOf="#+id/imagetrail2"
app:layout_constraintStart_toStartOf="#+id/imagetrail2"
app:layout_constraintTop_toBottomOf="#+id/imagetrail2" />
<EditText
android:id="#+id/editcap2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintEnd_toEndOf="#+id/editcap"
app:layout_constraintStart_toStartOf="#+id/editcap"
app:layout_constraintTop_toBottomOf="#+id/editcap" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="Button"
app:layout_constraintEnd_toEndOf="#+id/editcap2"
app:layout_constraintStart_toStartOf="#+id/editcap2"
app:layout_constraintTop_toBottomOf="#+id/editcap2" />
Java code
private ImageView nimagetrial, nimagetrial2;
private EditText neditcap,neditcap2;
private Button nsave;
private Bitmap bitmap,bitmap1;
private
Uri filepath,filepath1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_n_trial);
nimagetrial = findViewById(R.id.imagetrial);
nimagetrial2 = findViewById(R.id.imagetrail2);
neditcap = findViewById(R.id.editcap);
neditcap2 = findViewById(R.id.editcap2);
nsave = findViewById(R.id.button3);
nimagetrial.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ImagePicker.Companion.with(nTrial.this)
.crop()
.compress(1040)
.maxResultSize(1270,1270)
.start(10);
}
});
nimagetrial2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ImagePicker.Companion.with(nTrial.this)
.crop()
.compress(1040)
.maxResultSize(1270,1270)
.start(20);
}
});
nsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
savetrialData();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 10 && resultCode == RESULT_OK){
filepath = data.getData();
try{
InputStream inputStream=getContentResolver().openInputStream(filepath);
bitmap= BitmapFactory.decodeStream(inputStream);
nimagetrial.setImageBitmap(bitmap);
}catch (Exception ex)
{
}
}else if (requestCode == 20 && resultCode == RESULT_OK){
filepath1 = data.getData();
try {
InputStream inputStream1 = getContentResolver().openInputStream(filepath1);
bitmap1 = BitmapFactory.decodeStream(inputStream1);
nimagetrial2.setImageBitmap(bitmap1);
}catch (Exception ex){
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void savetrialData() {
ProgressDialog dialog = new ProgressDialog(this);
dialog.setTitle("Trail Uploader");
dialog.show();
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference uploader = storage.getReference("ntrial"+new Random().nextInt(50));
uploader.putFile(filepath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
uploader.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(#NonNull Uri uri) {
dialog.dismiss();
FirebaseDatabase mFD = FirebaseDatabase.getInstance();
DatabaseReference mDR = mFD.getReference("Trial");
nTrailModel obj = new nTrailModel(neditcap.getText().toString(), neditcap2.getText().toString(),uri.toString(),uri.toString());
mDR.child(neditcap.getText().toString()).setValue(obj);
neditcap.setText("");
neditcap2.setText("");
nimagetrial.setImageResource(R.drawable.id);
nimagetrial2.setImageResource(R.drawable.payment_l);
}
});
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
float percent = (100*snapshot.getBytesTransferred())/snapshot.getTotalByteCount();
dialog.setMessage(" Uploadind T_T: "+(int)percent+" %");
}
});
}
}

Firebase error uploading data through app android studio

This is the error i am getting i am trying to upload/update/delete information to firebase on the app. It shows and the dialog box but when I click save/view changes it crashes and does not work.
ERROR
Process: com.coffeeshopapp.ruhul08.myapplication, PID: 1131
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.coffeeshopapp.ruhul08.myapplication/com.coffeeshopapp.ruhul08.myapplication.FoodDetails}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3086)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3229)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1926)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:6981)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.coffeeshopapp.ruhul08.myapplication.FoodDetails.onCreate(FoodDetails.java:52)
at android.app.Activity.performCreate(Activity.java:7326)
at android.app.Activity.performCreate(Activity.java:7317)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3066)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3229) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1926) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:6981) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445) 
I/Process: Sending signal. PID: 1131 SIG: 9
Process 1131 terminated.
CODE
public class AdminFoodList extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
//RelativeLayout rootLayout;
FloatingActionButton fab;
//Firebase
FirebaseDatabase database;
DatabaseReference foodList;
FirebaseStorage storage;
StorageReference storageReference;
String categoryId="";
FirebaseRecyclerAdapter<Foods, FoodViewHolder> adapter;
DrawerLayout drawer;
private EditText editName, editDescription, editPrice, editDiscount;
private Button btnSelect;
private Button btnUpload;
Foods newFood;
Uri saveUri;
private final int PICK_IMAGE_REQUEST = 71;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_food_list);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
database = FirebaseDatabase.getInstance();
foodList = database.getReference("Foods");
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
//Init
recyclerView = (RecyclerView)findViewById(R.id.recycler_food);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
if (getIntent() != null){
categoryId = getIntent().getStringExtra("CategoryId");
}
if(!categoryId.isEmpty() && categoryId != null){
loadListFood(categoryId);
}
// rootLayout = (RelativeLayout)findViewById(R.id.rootLayout);
fab = (FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showAddFoodDialog();
}
});
}
private void showAddFoodDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(com.coffeeshopapp.app.myapplication.AdminFoodList.this);
alertDialog.setTitle("Add new Food");
alertDialog.setMessage("Please fill full information");
LayoutInflater inflater = this.getLayoutInflater();
View add_menu_layout = inflater.inflate(R.layout.add_new_food_layout,null);
editName = add_menu_layout.findViewById(R.id.edit_Name);
editDescription = add_menu_layout.findViewById(R.id.edit_Description);
editPrice = add_menu_layout.findViewById(R.id.edit_Price);
editDiscount = add_menu_layout.findViewById(R.id.edit_Discount);
btnSelect = add_menu_layout.findViewById(R.id.btn_select);
btnUpload = add_menu_layout.findViewById(R.id.btn_upload);
//event for button
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chooseImage(); //let user choose image from gallery and then save it to url of this image
}
});
btnUpload.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
uploadImage();
}
});
alertDialog.setView(add_menu_layout);
alertDialog.setIcon(R.drawable.ic_shopping_cart);
alertDialog.setPositiveButton("Save/View Changes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
if(newFood != null)
{
foodList.push().setValue(newFood);
Snackbar.make(drawer, "New Food "+newFood.getName()+" was added", Snackbar.LENGTH_SHORT)
.show();
}
}
});
alertDialog.setNegativeButton("Back", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
alertDialog.show();
}
private void uploadImage() {
if (saveUri != null)
{
final ProgressDialog mDialog = new ProgressDialog(this);
mDialog.setMessage("Uploading..");
mDialog.show();
String imageName = UUID.randomUUID().toString();
final StorageReference imageFolder = storageReference.child("images/"+imageName);
imageFolder.putFile(saveUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>(){
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mDialog.dismiss();
Toast.makeText(com.coffeeshopapp.app.myapplication.AdminFoodList.this, "Uploaded!!!", Toast.LENGTH_SHORT).show();
imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
newFood = new Foods();
newFood.setName(editName.getText().toString());
newFood.setDescription(editDescription.getText().toString());
newFood.setPrice(editPrice.getText().toString());
newFood.setDiscount(editDiscount.getText().toString());
newFood.setMenuId(categoryId);
newFood.setImage(uri.toString());
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e){
mDialog.dismiss();
Toast.makeText(com.coffeeshopapp.app.myapplication.AdminFoodList.this, ""+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());
mDialog.setMessage("Uploaded"+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);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data !=null && data.getData()!=null)
{
saveUri = data.getData();
btnSelect.setText("Your image is selected!");
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if(item.getTitle().equals(Common.UPDATE))
{
showUpdateFoodDialog(adapter.getRef(item.getOrder()).getKey(),adapter.getItem(item.getOrder()));
}
else if(item.getTitle().equals(Common.Delete))
{
deleteFood(adapter.getRef(item.getOrder()).getKey());
}
return super.onContextItemSelected(item);
}
private void showUpdateFoodDialog(final String key, final Foods item) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(com.coffeeshopapp.app.myapplication.AdminFoodList.this);
alertDialog.setTitle("Edit Food");
alertDialog.setMessage("Please fill full information");
LayoutInflater inflater = this.getLayoutInflater();
View add_menu_layout = inflater.inflate(R.layout.add_new_food_layout,null);
editName = add_menu_layout.findViewById(R.id.edit_Name);
editDescription = add_menu_layout.findViewById(R.id.edit_Description);
editPrice = add_menu_layout.findViewById(R.id.edit_Price);
editDiscount = add_menu_layout.findViewById(R.id.edit_Discount);
editName.setText(item.getName());
editDescription.setText(item.getDescription());
editPrice.setText(item.getPrice());
editDiscount.setText(item.getDiscount());
btnSelect = add_menu_layout.findViewById(R.id.btn_select);
btnUpload = add_menu_layout.findViewById(R.id.btn_upload);
//event for button
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chooseImage(); //let user choose image from gallery and then save it to url of this image
}
});
btnUpload.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
changeImage(item);
}
});
alertDialog.setView(add_menu_layout);
alertDialog.setIcon(R.drawable.ic_shopping_cart);
alertDialog.setPositiveButton("Save/View Changes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
//update info
item.setName(editName.getText().toString());
item.setPrice(editPrice.getText().toString());
item.setDiscount(editDiscount.getText().toString());
item.setDescription(editDescription.getText().toString());
foodList.child(key).setValue(item);
Snackbar.make(drawer, "food "+item.getName()+" was updated", Snackbar.LENGTH_SHORT)
.show();
}
});
alertDialog.setNegativeButton("Back", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
alertDialog.show();
}
private void loadListFood(String categoryId) {
adapter = new FirebaseRecyclerAdapter<Foods, FoodViewHolder>(
Foods.class,
R.layout.food_item,
FoodViewHolder.class,
foodList.orderByChild("MenuId").equalTo(categoryId))
{
#Override
protected void populateViewHolder(FoodViewHolder viewHolder, Foods model, int position) {
viewHolder.food_name.setText(model.getName());
Picasso.get().load(model.getImage()).into(viewHolder.food_image);
final Foods local = model;
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
//code later
}
});
}
};
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
}
private void changeImage(final Foods item){
if (saveUri != null)
{
final ProgressDialog mDialog = new ProgressDialog(this);
mDialog.setMessage("Uploading..");
mDialog.show();
String imageName = UUID.randomUUID().toString();
final StorageReference imageFolder = storageReference.child("images/"+imageName);
imageFolder.putFile(saveUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>(){
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mDialog.dismiss();
Toast.makeText(com.coffeeshopapp.app.myapplication.AdminFoodList.this, "Uploaded!!!", Toast.LENGTH_SHORT).show();
imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
item.setImage(uri.toString());
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e){
mDialog.dismiss();
Toast.makeText(com.coffeeshopapp.app.myapplication.AdminFoodList.this, ""+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());
mDialog.setMessage("Uploaded"+progress+"%");
}
});
}
}
private void deleteFood(String key){
foodList.child(key).removeValue();
}
}
this is the code for the xml activity_admin_food_list. I am not sure about the floating action button as this is included in the code for this xml page.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rootLayout"
tools:context=".FoodList">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_food"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
app:layout_constraintBottom_toBottomOf="parent"
tools:layout_editor_absoluteX="61dp" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:layout_marginStart="16dp"
android:layout_marginTop="712dp"
android:layout_marginEnd="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toEndOf="#+id/recycler_food"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/addicon" />
</android.support.design.widget.CoordinatorLayout>
fab = (FloatingActionButton)findViewById(R.id.fab);
is not being found in your XML R.layout.activity_admin_food_list, check if you have your fab button there

when load GooglePlaceAutocomplete Fragment in second time its crashed

I'm working on PlaceAutocompleteFragment. I load this Fragment Simply in the first time and when the load in a second time then show some error and its crashed.
Error is : java.lang.IllegalArgumentException: Binary XML file line
11: Duplicate id 0x7f090251, tag null, or parent id 0x7f090193 with another fragment for
com.google.android.gms.location.places.ui.PlaceAutocompleteFragment
public class MakeReservationFragment extends BaseFragment implements
GoogleApiClient.OnConnectionFailedListener , PlaceSelectionListener {
View mMakeReservationView;
ProgressBar bar;
FrameLayout layout;
private static final LatLngBounds BOUNDS_GREATER_SYDNEY = new
LatLngBounds(
new LatLng(-34.041458, 150.790100), new LatLng(-33.682247, 151.383362));
#Override
public View setContentView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mMakeReservationView = inflater.inflate(R.layout.frag_make_reservation, container, false);
initView();
return mMakeReservationView;
}
private void initView() {
setHeaderBarTitle("RESERVATION");
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getActivity().getFragmentManager().findFragmentById(R.id.place_fragment1);
autocompleteFragment.setOnPlaceSelectedListener(MakeReservationFragment.this);
autocompleteFragment.setHint("Search a Location");
autocompleteFragment.setBoundsBias(BOUNDS_GREATER_SYDNEY);
layout=(FrameLayout)mMakeReservationView.findViewById(R.id.framereserve1);
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onResume() {
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
setHeaderBarleftIcon(R.drawable.ic_home);
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
}
return false;
}
});
}
#Override
public void onPlaceSelected(Place place) {
}
#Override
public void onError(Status status) {
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode ==RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(getActivity(), data);
onPlaceSelected(place,0);
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(getActivity(), data);
this.onError(status,0);
}
}
else
{
if (resultCode == RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(getActivity(), data);
onPlaceSelected(place,1);
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(getActivity(), data);
onError(status,1);
}
}
}
private void onError(Status status, int i) {
Toast.makeText(getActivity(), "Place selection failed: " + status.getStatusMessage(),
Toast.LENGTH_SHORT).show();
}
private void onPlaceSelected(Place place, int i) {
try{
System.out.println("00000000 Place Darta IS 0 error" + place.getId()+","+place.getAddress()+","+place.getLatLng()+","+place.getLocale()+","+place.getName()+
","+place.getAttributions()+","+place.getViewport()+","+place.getPhoneNumber()+","+place.getPlaceTypes());
}
catch ( Exception e)
{
}
}
}
And XML code is:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="#+id/framereserve1"
android:background="#color/backgoound_dull"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/place_fragment1"
android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
android:layout_width="match_parent"
android:layout_height="50dp"/>

dm77 barcodescanner Zbar camera Preview delay in fragment

Hi I am using this library for my android bar code reader and it is working fine with activities but it give some what delay in initiate(Not smooth like when it use in the Activities)when use with the fragment any solution for this.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_gravity="top"
android:minHeight="?attr/actionBarSize"
android:background="#color/actionbar_opacity"
app:theme="#style/TransparentToolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<RelativeLayout
android:id="#+id/btn_enable_qr"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginBottom="55dp"
android:layout_marginLeft="40dp"
android:layout_marginRight="40dp"
android:gravity="bottom"
android:layout_alignParentBottom="true"
android:clickable="true"
android:layout_gravity="bottom"
android:background="#drawable/circle_layout_for_start_scan">
</RelativeLayout>
</RelativeLayout>
This is My Fragment & when application start I set this fragment to my main activity
public class ScannerFragment extends Fragment implements ZBarScannerView.ResultHandler {
private ZBarScannerView mScannerView;
private FrameLayout contentFrame;
RelativeLayout enableQR;
private static final int ZBAR_CAMERA_PERMISSION = 1;
public static ScannerFragment newInstance() {
return new ScannerFragment();
}
#SuppressLint("ClickableViewAccessibility")
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = null;
try {
rootView = inflater.inflate(R.layout.activity_full_scanner, container, false);
contentFrame = (FrameLayout) rootView.findViewById(R.id.content_frame);
enableQR = (RelativeLayout) rootView.findViewById(R.id.btn_enable_qr);
enableQR.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
launchActivity();
break;
}
case MotionEvent.ACTION_UP: {
releaseCamera();
}
}
return true;
}
});
} catch (Exception e) {
// Log.e(TAG, "onCreateView: " + e.toString());
}
return rootView;
}
#Override
public void onResume() {
super.onResume();
}
public void launchActivity() {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.CAMERA}, ZBAR_CAMERA_PERMISSION);
} else {
setUpQrScanner();
}
}
public void setUpQrScanner() {
mScannerView = new ZBarScannerView(getActivity());
mScannerView.setFormats(BarcodeFormat.ALL_FORMATS);
contentFrame.addView(mScannerView);
mScannerView.setResultHandler(ScannerFragment.this);
mScannerView.startCamera(-1);
mScannerView.setAutoFocus(true);
}
public void releaseCamera() {
mScannerView.stopCamera();
contentFrame.removeView(mScannerView);
}
#Override
public void handleResult(Result rawResult) {
try {
scannerSoundAndVibration();
} catch (Exception e) {}
Toast.makeText(getActivity(), "Result" + rawResult.getContents()+" TYPE: "+rawResult.getBarcodeFormat().getId(), Toast.LENGTH_LONG).show();
}
#Override
public void onPause() {
super.onPause();
}
private void scannerSoundAndVibration() {
/**
* scanner sound alert time in millisecond
*/
final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 200);
tg.startTone(ToneGenerator.TONE_CDMA_KEYPAD_VOLUME_KEY_LITE);
/**
* scanner vibration alert time in millisecond
*/
Vibrator v = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(250);
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case ZBAR_CAMERA_PERMISSION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
setUpQrScanner();
} else {
Toast.makeText(getActivity(), "Please grant camera permission to use the QR Scanner", Toast.LENGTH_SHORT).show();
}
return;
}
}
}

Android Firebase Retrieve Image Url

I want to get the DownloadUrl from an image I uploaded to Firebase but when I try loading it later, I only get a not found exception:
public class ProfileActivity extends AppCompatActivity{
private static final int CHOOSE_IMAGE = 200;
//Initialize items
EditText inputUsername, inputBirthday;
FloatingActionButton mainaction;
FloatingActionButton homeaction;
FloatingActionButton profileaction;
StorageReference profileimageRef;
String profileimageurl;
Button actionSaveProfile;
FirebaseAuth mAuth;
ProgressBar progressBar;
ImageView profileimage;
Boolean isfabopen;
Uri uriProfileImage;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
isfabopen = false;
mainaction = findViewById(R.id.fab_expand);
homeaction = findViewById(R.id.fab_home);
profileaction = findViewById(R.id.fab_profile);
inputUsername = findViewById(R.id.input_username);
inputBirthday = findViewById(R.id.input_birthday);
actionSaveProfile = findViewById(R.id.action_save_profile);
profileimage = findViewById(R.id.profile_image);
progressBar = findViewById(R.id.progressbar);
mAuth = FirebaseAuth.getInstance();
//Expand, collapse menu
mainaction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isfabopen)
{
ShowFab();
}else
{
CloseFab();
}
}
});
profileimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showImageChooser();
}
});
homeaction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ProfileActivity.this, MainActivity.class));
}
});
actionSaveProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveUserData(v);
}
});
loadUserData();
}
private void loadUserData() {
FirebaseUser user = mAuth.getCurrentUser();
//If no profile picture found
if(user.getPhotoUrl() != null)
{
String photoUrl = user.getPhotoUrl().toString();
//Set profile picture
Glide.with(this)
.load(user.getPhotoUrl().toString())
.into(profileimage);
}
//If no username found
if(user.getDisplayName() != null)
{
String username = user.getDisplayName();
//Insert display name
inputUsername.setText(user.getDisplayName());
}
}
private void saveUserData(View v)
{
String name = inputUsername.getText().toString().trim();
String birthtday = inputBirthday.getText().toString().trim();
//Check if has content
if(name.isEmpty())
{
Snackbar.make(v, R.string.message_username_empty, Snackbar.LENGTH_SHORT)
.setAction("Action", null).show();
inputUsername.requestFocus();
}else if(birthtday.isEmpty()) {
Snackbar.make(v, R.string.message_birthday_empty, Snackbar.LENGTH_SHORT)
.setAction("Action", null).show();
inputBirthday.requestFocus();
}
//Get user
FirebaseUser user = mAuth.getCurrentUser();
//Upload information
if(user != null && profileimageurl != null)
{
UserProfileChangeRequest profileChangeRequest = new UserProfileChangeRequest.Builder()
.setDisplayName(name)
.setPhotoUri(Uri.parse(profileimageurl))
.build();
Log.wtf("ImageURL3", profileimageurl);
//Show progressbar
progressBar.setVisibility(View.VISIBLE);
user.updateProfile(profileChangeRequest).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
//Hide progressbar
progressBar.setVisibility(View.GONE);
if(task.isSuccessful())
{
Toast.makeText(ProfileActivity.this, R.string.message_profile_updated, Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(ProfileActivity.this, task.getException().getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
//When got activity result from showImageChooser
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Check if result is ok
if(requestCode == CHOOSE_IMAGE && resultCode == RESULT_OK && data !=null && data.getData() != null)
{
//Save uri of image
uriProfileImage = data.getData();
try
{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uriProfileImage);
profileimage.setImageBitmap(bitmap);
uploadToFirebase();
}catch (Exception ex)
{
ex.printStackTrace();
}
}
}
private void uploadToFirebase() {
//Select destination filename, folder
profileimageRef = FirebaseStorage.getInstance().getReference("profilepictures/" + System.currentTimeMillis() + ".jpg");
Log.wtf("ImageURL", profileimageRef.toString());
//Upload image
if(uriProfileImage != null)
{
//Show progressbar
progressBar.setVisibility(View.VISIBLE);
profileimageRef.putFile(uriProfileImage).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
//Hide progressbar
progressBar.setVisibility(View.GONE);
//Check if was successful
if(task.isSuccessful())
{
//Set profile image url
profileimageurl = task.getResult().toString();
Log.wtf("ImageURL2", profileimageurl);
}else
{
Toast.makeText(ProfileActivity.this, task.getException().getLocalizedMessage() , Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void showImageChooser()
{
//Create chooser
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
//Start chooser activity and wait for result
startActivityForResult(Intent.createChooser(intent, getString(R.string.label_profile_pic_chooser)), CHOOSE_IMAGE);
}
private void ShowFab() {
//Bool for menu open
isfabopen = true;
//Set buttons visible
homeaction.setVisibility(View.VISIBLE);
profileaction.setVisibility(View.VISIBLE);
//Rotate main button
mainaction.animate().rotation(135f);
//Expanding to top
homeaction.animate().translationY(getResources().getDimension(R.dimen.standard_100)).rotation(0f);
profileaction.animate().translationY(getResources().getDimension(R.dimen.standard_55)).rotation(0f);
}
private void CloseFab() {
//Bool for menu closed
isfabopen = false;
//Hide buttons
homeaction.setVisibility(View.VISIBLE);
profileaction.setVisibility(View.VISIBLE);
//Rotate main button
mainaction.animate().rotation(0f);
//Collapsing
homeaction.animate().translationY(getResources().getDimension(R.dimen.standard_0)).rotation(135f);
profileaction.animate().translationY(getResources().getDimension(R.dimen.standard_0)).rotation(135f);
}
//Check if user is logged in
#Override
protected void onStart() {
super.onStart();
//Check if user is already loggged in
if(mAuth.getCurrentUser() == null)
{
finish();
startActivity(new Intent(ProfileActivity.this, LoginActivity.class));
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
//Go back to home activity
finish();
startActivity(new Intent(ProfileActivity.this, MainActivity.class));
}
}
XML Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RelativeLayout
android:id="#+id/relativeLayout2"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#color/colorPrimary"
android:backgroundTint="#color/colorPrimary"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<de.hdodenhof.circleimageview.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/profile_image"
android:layout_width="156dp"
android:layout_height="156dp"
android:src="#drawable/camera_placeholder"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/relativeLayout2">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingLeft="#dimen/standard_23"
android:paddingRight="#dimen/standard_23">
<EditText
android:id="#+id/input_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#color/colorProfileAccent"
android:hint="#string/label_username"
android:inputType="textPersonName"
android:paddingBottom="15dp"
android:textColor="#color/colorProfileAccent"
android:textColorHint="#color/colorProfileAccent" />
<EditText
android:id="#+id/input_birthday"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#color/colorProfileAccent"
android:hint="#string/label_birthday"
android:inputType="textPersonName"
android:paddingBottom="15dp"
android:textColor="#color/colorProfileAccent"
android:textColorHint="#color/colorProfileAccent" />
<Button
android:id="#+id/action_save_profile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="7dp"
android:background="#drawable/rounded_btn_profile"
android:text="#string/apply_changes"
android:textColor="#color/colorProfileText" />
</LinearLayout>
<ProgressBar
android:id="#+id/progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:visibility="gone" />
</RelativeLayout>
<android.support.design.widget.CoordinatorLayout
android:id="#+id/coordinatorLayout"
android:layout_width="wrap_content"
android:layout_height="197dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent">
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_home"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/standard_23"
android:rotation="90"
android:visibility="gone"
app:fabSize="mini"
app:srcCompat="#drawable/ic_home" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_profile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/standard_23"
android:rotation="0"
android:translationY="#dimen/standard_55"
android:visibility="gone"
app:fabSize="mini"
app:srcCompat="#drawable/ic_account_box" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_expand"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:fabSize="normal"
app:srcCompat="#drawable/ic_add" />
</android.support.design.widget.CoordinatorLayout>
</android.support.constraint.ConstraintLayout>
I only get a java.io.FileNotFoundException: No such file or directory exception. Earlier I tried saving it with an Success-Listener as it's shown here: https://stackoverflow.com/a/50743192/6274419. But that also hadn't worked because the function doesn't exist in the newer Firebase version.
In general I want to display a profile picture and the username which are saved to Firebase and retrieved on next application startup.
Thanks in Advance!
It takes some time to upload the image in firebase. So you can only retrieve the image when it is completely saved in database. Please call the loadUserData() method in OnSuccess and let me know if it works.
private void uploadToFirebase() {
//Select destination filename, folder
profileimageRef = FirebaseStorage.getInstance().getReference("profilepictures/" + System.currentTimeMillis() + ".jpg");
Log.wtf("ImageURL", profileimageRef.toString());
//Upload image
if(uriProfileImage != null)
{
//Show progressbar
progressBar.setVisibility(View.VISIBLE);
profileimageRef.putFile(uriProfileImage).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
//Hide progressbar
progressBar.setVisibility(View.GONE);
//Check if was successful
if(task.isSuccessful())
{
//Set profile image url
profileimageurl = task.getResult().toString();
loadUserData();
Log.wtf("ImageURL2", profileimageurl);
}else
{
Toast.makeText(ProfileActivity.this, task.getException().getLocalizedMessage() , Toast.LENGTH_SHORT).show();
}
}
});
Solved it now by using another structure/method for retrieving the url with a UploadTask:
private void uploadToFirebase() {
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReference();
//Select destination filename, folder
final StorageReference profileimageRef = storageRef.child("profilepictures/" + System.currentTimeMillis() + ".jpg");
UploadTask uploadTask = profileimageRef.putFile(uriProfileImage);
Log.wtf("ImageURL", profileimageRef.toString());
//Upload image
if(uriProfileImage != null)
{
//Show progressbar
progressBar.setVisibility(View.VISIBLE);
Task<Uri> uriTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful())
{
throw task.getException();
}
return profileimageRef.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
progressBar.setVisibility(View.GONE);
if(task.isSuccessful()) {
profileimageurl = task.getResult().toString();
}
}
});
}
}

Categories

Resources