i did android app using java and firebase.
the app is like instagram/blog and when you touch a post (in the main page) you forward to fragment that suppose to be the details of the specific post you touched, but when i touch the post i forward to the fragment, see it for 2 sec (without the details, just the body of the xml) and the app crash with-E/AndroidRuntime: FATAL EXCEPTION: main error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.traveleisure, PID: 17959
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.Map.get(java.lang.Object)' on a null object reference
at com.example.traveleisure.Model.Destination.fromMap(Destination.java:65)
at com.example.traveleisure.Model.ModelFirebase$5.onComplete(ModelFirebase.java:108)
at com.google.android.gms.tasks.zzi.run(com.google.android.gms:play-services-tasks##18.0.1:1)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
here is piece of the code in (Destination.java:65):
#Entity
public class Destination {
#PrimaryKey
#NonNull
private String id;
private String titleDestination;
private String category;
private String destination;
private Long CreatedDate;
private Long UpdatedDate;
private String imageUrl;
private String userId;
private String userName;
private String userPic;
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("id", id);
result.put("titleDestination", titleDestination);
result.put("category", category);
result.put("destination", destination);
result.put("CreatedDate", FieldValue.serverTimestamp());
result.put("lastUpdated", FieldValue.serverTimestamp());
result.put("imageUrl", imageUrl);
result.put("userId", userId);
result.put("userName", userName);
result.put("userPic",userPic);
return result;
}
public Map<String, Object> toMapUpdateUser() {
HashMap<String, Object> result = new HashMap<>();
result.put("id", id);
result.put("titleDestination", titleDestination);
result.put("category", category);
result.put("destination", destination);
result.put("imageUrl", imageUrl);
result.put("userId", userId);
result.put("userName", userName);
result.put("userPic",userPic);
return result;
}
public void fromMap(Map<String, Object> map) {
id = (String)map.get("id"); //-----------------Line 65---------------
titleDestination = (String)map.get("titleDestination");
category = (String)map.get("category");
destination = (String)map.get("destination");
imageUrl = (String)map.get("imageUrl");
userId = (String)map.get("userId");
userName = (String)map.get("userName");
Timestamp ts = (Timestamp) map.get("CreatedDate");
Timestamp ts1 = (Timestamp) map.get("lastUpdated");
CreatedDate = ts.getSeconds();
UpdatedDate = ts1.getSeconds();
userPic= (String) map.get("userPic");
}
//--downs here all the getters and setters--
}
here is piece of the code in (ModelFirebase.java:108):
public class ModelFirebase {
public static FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
public static FirebaseFirestore db = FirebaseFirestore.getInstance();
FirebaseStorage storage = FirebaseStorage.getInstance();
public static int destinationsCounter=0;
public void deleteDestination(Destination destination) {
db.collection("Deleted Destinations") .document(destination.getId()).set(destination.toMap()).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("TAG", "-Destination remove Successfully-");
}
});
}
public interface GetAllDestinationsListener{
void onComplete(List<Destination> list);
}
public void addDestination(Destination destination, final Model.AddDestinationListener listener) {
db.collection("destinations")
.document(destination.getId()).set(destination.toMap()).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("TAG", "-Destination added Successfully-");
listener.onComplete();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w("TAG", "-Error adding destination-", e);
listener.onComplete();
}
});
}
public void getAllDestinations(Long lastUpdated, final GetAllDestinationsListener listener) {
Timestamp ts = new Timestamp(lastUpdated, 0);
db.collection("destinations").whereGreaterThan("lastUpdated", ts)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
List<Destination> destinationList = new LinkedList<Destination>();
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Destination dst = new Destination();
dst.fromMap(document.getData());
destinationList.add(dst);
Log.d("TAG", document.getId() + " => " + document.getData()); }
} else {
Log.d("TAG", "Error getting documents: ", task.getException());
}
listener.onComplete(destinationList);
}
});
}
public void getDestination(String id, final Model.GetDestinationListener listener) {
db.collection("destination").document(id).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
Destination destination = null;
if (task.isSuccessful()) {
DocumentSnapshot doc = task.getResult();
if (doc!=null) {
destination = new Destination();
destination.fromMap(task.getResult().getData()); //------Line 108--
}
}
listener.onComplete(destination);
}
});
}
public void delete(Destination destination, Model.DeleteDestinationListener listener) {
db.collection("destinations").document(destination.getId()).delete().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
listener.onComplete();
}
});
}
public interface Listener<T>{
void onComplete();
void onFail();
}
public static void registerUserAccount(final String fullName, String password, final String email,final String profilePic, final Listener<Boolean> listener) {
if (firebaseAuth.getCurrentUser() != null){
firebaseAuth.signOut();
}
if (firebaseAuth.getCurrentUser() == null &&
fullName != null && !fullName.equals("") &&
password != null && !password.equals("") &&
email != null && !email.equals("")){
Map<String,Object> data = new HashMap<>();
firebaseAuth.createUserWithEmailAndPassword(email, password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
Toast.makeText(MyApp.context, "User registered", Toast.LENGTH_SHORT).show();
data.put("id",FirebaseAuth.getInstance().getCurrentUser().getUid());
data.put("profilePic",null);
data.put("fullName", fullName);
data.put("email", email);
data.put("password", password);
db.collection("userProfileData").document(email).set(data).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("TAG", "User has created in userProfileData Collection");
User user = new User(null,fullName,email,profilePic);
setUserAppData(email);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MyApp.context, "Fails to create user and upload data: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
listener.onComplete();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MyApp.context, e.getMessage(), Toast.LENGTH_SHORT).show();
listener.onFail();
}
});
}
}
public static void uploadUserData(final String fullName, final String email){
Map<String,Object> data = new HashMap<>();
data.put("fullName", fullName);
data.put("email", email);
db.collection("userProfileData").document(email).set(data).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(MyApp.context, "User has created in userProfileData Collection", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MyApp.context, "Fails to create user and upload data: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public static void updateUserProfile(User user){
if(user.profilePic==null){
db.collection("userProfileData").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
if(document.getData().get("id").equals(user.id)){
if(document.getData().get("profilePic")!=null){
String url= (String) document.getData().get("profilePic");
user.profilePic=url;
}
db.collection("userProfileData")
.document(User.getInstance().email).set(user.toMap());
}
}
} else {
Log.d("TAG", "Error getting documents: ", task.getException());
}
}
});
}else{
db.collection("userProfileData")
.document(User.getInstance().email).set(user.toMap());
}
db.collection("destination").whereEqualTo("userId",user.id).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>(){
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot doc : task.getResult()) {
Destination dst= new Destination();
dst.setCategory(doc.getData().get("category").toString());
dst.setId(doc.getData().get("id").toString());
dst.setImageUrl(doc.getData().get("imageUrl").toString());
dst.setDestination(doc.getData().get("destination").toString());
dst.setTitleDestination(doc.getData().get("titleDestination").toString());
dst.setUserId(doc.getData().get("userId").toString());
dst.setUserName(user.fullName);
if( user.profilePic!=null){
dst.setUserPic(user.profilePic);
}
Log.d("update","destination Data: "+dst.getUserPic());
Log.d("update","destination Data: "+dst.getUserName());
db.collection("destinations")
.document(dst.getId()).set(dst.toMap());
}
}
}
});
}
public static void CreateUserProfile(String email,String fullName, String password, String profilePic) {
Map<String, Object> data = new HashMap<>();
if (email != null)
data.put("email",email);
if (fullName != null)
data.put("fullName", fullName);
if (profilePic != null)
data.put("profilePic", profilePic);
if (password != null)
data.put("password", password);
Log.d("TAG","email: "+email);
Log.d("TAG","fullName: "+fullName);
Log.d("TAG","profilePic: "+profilePic);
Log.d("TAG","password: "+password); db.collection("userProfileData").document(User.getInstance().email).set(data).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(MyApp.context, "-Profile Updates Successfully- " , Toast.LENGTH_SHORT).show();
}
});
}
public static void loginUser(final String email, String password, final Listener<Boolean> listener){
Log.d("TAG", "LOGIN");
if (email != null && !email.equals("") && password != null && !password.equals("")){
if (firebaseAuth.getCurrentUser() != null) {
firebaseAuth.signOut();
}
firebaseAuth.signInWithEmailAndPassword(email, password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
Toast.makeText(MyApp.context, "Login Succeeded!", Toast.LENGTH_SHORT).show();
setUserAppData(email);
listener.onComplete();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MyApp.context, "Failed to login: " + e.getMessage(), Toast.LENGTH_SHORT).show();
listener.onFail();
}
});
}
else {
Toast.makeText(MyApp.context, "Please fill both data fields", Toast.LENGTH_SHORT).show();
}
}
public static void setUserAppData(String email) {
db.collection("userProfileData").document(email).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()){
User.getInstance().profilePic=(String) task.getResult().get("profilePic");
User.getInstance().fullName = (String) task.getResult().get("fullName");
User.getInstance().password = (String) task.getResult().get("password");
User.getInstance().email = email;
User.getInstance().id = firebaseAuth.getUid();
}
}
});
}
public static void signOut(){
FirebaseAuth mAuth = FirebaseAuth.getInstance();
mAuth.signOut();
}
public static void getImageFromFireBase(String userId){ db.collection("userProfileData").whereEqualTo("id",userId).get().addOnCompleteListener((OnCompleteListener<QuerySnapshot>) task -> {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d("TAG", "test" + document.getId() + " => " + document.getData().get("profilePic"));
User.getInstance().FBpic=(String) document.getData().get("profilePic");
}
} else {
Log.d("TAG", "Error getting documents: ", task.getException());
}
});
}
public void uploadImage(Bitmap imageBmp, String name, Model.UploadImageListener listener){
final StorageReference imagesRef = storage.getReference().child("images").child(name);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = imagesRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(Exception exception) {
listener.onComplete(null);
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
imagesRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri downloadUrl = uri;
listener.onComplete(downloadUrl.toString());
}
});
}
});
}
}
Details xml:
<?xml version="1.0" encoding="utf-8"?>
<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">
<androidx.cardview.widget.CardView
android:id="#+id/cardView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="4dp"
android:layout_marginTop="4dp"
android:layout_marginEnd="4dp"
android:layout_marginBottom="4dp"
app:cardCornerRadius="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#D2000000">
<ImageView
android:id="#+id/details_image"
android:layout_width="0dp"
android:layout_height="275dp"
android:layout_marginStart="6dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="6dp"
android:layout_marginBottom="6dp"
android:scaleType="centerCrop"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/details_detailDestination"
tools:ignore="MissingConstraints" />
<TextView
android:id="#+id/details_category"
android:layout_width="0dp"
android:layout_height="24dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:fontFamily="#font/thin"
android:hint="Category"
android:textColor="#FFFFFF"
android:textColorHint="#FFFFFF"
android:textSize="18sp"
app:layout_constraintStart_toEndOf="#+id/detailsprofile_profile_im"
app:layout_constraintTop_toBottomOf="#+id/details_destinationTitle" />
<TextView
android:id="#+id/details_destinationTitle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="32dp"
android:fontFamily="#font/bold"
android:text="Destination Title"
android:textColor="#FFFFFF"
android:textSize="18sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/detailsprofile_profile_im"
app:layout_constraintTop_toBottomOf="#+id/details_nickname"
tools:ignore="MissingConstraints" />
<TextView
android:id="#+id/details_nickname"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_marginStart="8dp"
android:layout_marginTop="24dp"
android:fontFamily="#font/regular"
android:text="Nickname"
android:textColor="#0287F1"
android:textSize="18sp"
app:layout_constraintStart_toEndOf="#+id/detailsprofile_profile_im"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="MissingConstraints" />
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/detailsprofile_profile_im"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:src="#drawable/ic_round_person_grey"
app:civ_border_color="#FF000000"
app:civ_border_width="2dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="MissingConstraints" />
<TextView
android:id="#+id/details_detailDestination"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="44dp"
android:layout_marginEnd="32dp"
android:background="#drawable/style_destinationdetails"
android:fontFamily="#font/thin"
android:paddingLeft="6sp"
android:paddingTop="2sp"
android:paddingRight="6sp"
android:paddingBottom="2sp"
android:text="Destination"
android:textColor="#FFFFFF"
android:textColorHint="#FFFFFF"
android:textSize="16sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/details_category" />
<ImageView
android:id="#+id/details_closeImg"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_baseline_close_24" />
<ImageView
android:id="#+id/details_deleteImg"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
app:layout_constraintEnd_toStartOf="#+id/details_closeImg"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_baseline_delete_24" />
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
i would ike if someone will know what can be the problem... i'm trying to fix it for days but can't find the solution...
Thank you in advance!
Make sure you are querying correct id & task.getResult().getData() is not null in ModelFirebase.java class before line number 108
public void getDestination(String id, final Model.GetDestinationListener listener) {
db.collection("destination").document(id).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
Destination destination = null;
if (task.isSuccessful()) {
DocumentSnapshot doc = task.getResult();
if (doc!=null && doc.getData()!=null) {
destination = new Destination();
destination.fromMap(task.getResult().getData());
}
}
listener.onComplete(destination);
}
});
}
Related
I am trying to save the radio button user response in Firestore under the UID. I have two choices yes and no to the question. It only works one time that the user selects a choice with a button pressed but if the user wants to change the answer it does not update (replace the old response).
I am wondering if anyone can help so that the selected response can be updated.
buttonfor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String yes = yesButton.getText().toString();
String no = yesButton.getText().toString();
Map<String, Object> user = new HashMap<>();
if (radioGroup.getCheckedRadioButtonId() == R.id.question_a1) {
user.put("I am wiling to participate", yes);
} else if (radioGroup.getCheckedRadioButtonId() == R.id.question_a2){
user.put("I am wiling to participate", no);
}
userID = fAuth.getCurrentUser().getUid();
fStore.collection("users").document(userID).set(user).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(question.this, "User Response Saved", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(question.this, "Error!", Toast.LENGTH_SHORT).show();
Log.d(TAG, e.toString());
}
});
}
});
In addition, I also tried but the response does not update in Firestore
if (yesButton.isChecked()){
user.put("I am wiling to participate", yes);
} else if (noButton.isChecked()){
user.put("I am wiling to participate", no);
}
And with update instead of set also did not work...
fStore.collection("users").document(userID).update(user).addOnSuccessListener(new OnSuccessListener<Void>()
To solve this, first, you have to create a layout that contains two radio buttons:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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">
<RadioGroup
android:id="#+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
<RadioButton
android:id="#+id/yesRadioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Yes"/>
<RadioButton
android:id="#+id/noRadioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No"/>
</RadioGroup>
</androidx.constraintlayout.widget.ConstraintLayout>
Then inside your activity, you have to find them by id and attach a real-time listener. Assuming that your Firestore schema looks like this:
Firestore-root
|
--- users
|
--- $uid
|
--- participate: true
|
--- //other fields
Here is the code:
Define them as members of the class (global variables):
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference uidRef = db.collection("users").document(uid);
Add inside onCreate:
RadioButton yesRadioButton = findViewById(R.id.yesRadioButton);
RadioButton noRadioButton = findViewById(R.id.noRadioButton);
uidRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot snapshot, #Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.w(TAG, "Listen failed.", e);
return;
}
if (snapshot != null && snapshot.exists()) {
Boolean participate = snapshot.getBoolean("participate");
if(participate != null) {
if (participate) {
yesRadioButton.setChecked(true);
} else {
noRadioButton.setChecked(true);
}
}
}
}
});
Here is to code for attaching a click listener on each radio button:
yesRadioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (yesRadioButton.isChecked()) {
updateParticipate(true);
}
}
});
noRadioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (noRadioButton.isChecked()) {
updateParticipate(false);
}
}
});
And here is the method which is responsible for the update:
void updateParticipate(boolean participate) {
Map<String, Object> update = new HashMap<>();
update.put("participate", participate);
uidRef.update(update).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(getApplicationContext(), "Updated: " + participate, Toast.LENGTH_SHORT).show();
}
});
}
Sorry I am not able to comment yet!
If your question is not solved yet, please may you provide more code because per my check on the code snippet you provided I cannot detect where the error is coming from.
When submitting to Firebase, only photos are sent, without text and database as such.
I do according to the guide, but I don’t understand what is the reason.
The guide probably uses the deprecated getDownloadUrl() method, but the photo does not suffer from this. I do not understand the reason for this, since I am still new in this area, please help, I no longer understand what to do. To understand something, look at Maineenter image description here
public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE_REQUEST = 1;
private Button mButtonChooseImage;
private Button mButtonUpload;
private TextView mTextViewShowUploads;
private EditText mEditTextFileName;
private ImageView mImageView;
private ProgressBar mProgressBar;
private Uri mImageUri;
private StorageReference mStorageRef;
private DatabaseReference mDatabaseRef;
private StorageTask mUploadTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButtonChooseImage = findViewById(R.id.button_choose_im);
mButtonUpload = findViewById(R.id.button_upload);
mTextViewShowUploads = findViewById(R.id.text_view_show);
mEditTextFileName = findViewById(R.id.edit_text_file_name);
mImageView = findViewById(R.id.image_view);
mProgressBar = findViewById(R.id.progress_bar);
mStorageRef = FirebaseStorage.getInstance().getReference("uploads");
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
mButtonChooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
mButtonUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mUploadTask != null && mUploadTask.isInProgress()) {
Toast.makeText(MainActivity.this, "Upload in progress", Toast.LENGTH_SHORT).show();
} else {
uploadFile();
}
}
});
mTextViewShowUploads.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
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) {
mImageUri = data.getData();
Picasso.get().load(mImageUri).into(mImageView);
}
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void uploadFile() {
if (mImageUri != null) {
StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
mUploadTask = fileReference.putFile(mImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress(0);
}
}, 500);
Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_LONG).show();
Upload upload = new Upload(mEditTextFileName.getText().toString().trim(),
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString());
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(upload);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.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());
mProgressBar.setProgress((int) progress);
}
});
} else {
Toast.makeText(this, "No file selected", Toast.LENGTH_SHORT).show();
}
}
}
Класс Upload
public class Upload {
private String mName;
private String mImageUrl;
public Upload(){
}
public Upload(String name, String imageUrl) {
this.mName = name;
this.mImageUrl = imageUrl;
}
public String getName() {
return mName;
}
public void setName(String name) {
this.mName = mName;
}
public String getImageUrl() {
return mImageUrl;
}
public void setImageUrl(String imageUrl) {
this.mImageUrl = mImageUrl;
}
}
activity_main
<RelativeLayout 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:padding="16dp"
tools:context=".MainActivity">
<Button
android:id="#+id/button_choose_im"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose" />
<EditText
android:id="#+id/edit_text_file_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_toEndOf="#+id/button_choose_im"
android:hint="Enter"
android:minHeight="48dp" />
<ImageView
android:id="#+id/image_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/progress_bar"
android:layout_below="#id/edit_text_file_name"
android:layout_marginTop="16dp" />
<ProgressBar
android:id="#+id/progress_bar"
style="#style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#id/button_upload"
android:layout_alignParentStart="true"
android:layout_marginBottom="16dp" />
<Button
android:id="#+id/button_upload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="16dp"
android:text="Upload" />
<TextView
android:id="#+id/text_view_show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/button_upload"
android:layout_alignBottom="#+id/button_upload"
android:layout_marginStart="25dp"
android:layout_toEndOf="#+id/button_upload"
android:gravity="center"
android:text="Show"
android:textSize="16sp" />
</RelativeLayout>
I am making an android application which is sort of a social media app
but when I am trying to put image from gallery or from camera for profile or cover this problem occurs.
I want the user to select a photo from his gallery or take a new picture using camera and then upload the image to Firebase Storage.
User does not have permission to access this object using Firebase Storage.
There are my permissions ..
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
My Java Code:
FirebaseAuth firebaseAuth;
FirebaseUser user;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
StorageReference storageReference;
String storagePath = "Uers_Profile_Cover_Imgs/";
ImageView avatartv, coverTv;
TextView nameTv, emailTv, phoneTv;
FloatingActionButton fab;
ProgressDialog pd;
private static final int CAMERA_REQUEST_CODE = 100;
private static final int STORAGE_REQUEST_CODE = 200;
private static final int IMAGE_PICK_GALLERY_CODE = 300;
private static final int IMAGE_PICK_CAMERA_CODE = 400;
String cameraPermissions[];
String storagePermission[];
Uri image_uri;
String profileOrCoverPhoto;
public ProfileFragment() {
// 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_profile, container, false);
firebaseAuth = FirebaseAuth.getInstance();
user = firebaseAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Users");
storageReference = getInstance().getReference();
cameraPermissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
avatartv = view.findViewById(R.id.avatarTv);
coverTv = view.findViewById(R.id.coverTv);
nameTv = view.findViewById(R.id.name);
emailTv = view.findViewById(R.id.category);
phoneTv = view.findViewById(R.id.location);
fab = view.findViewById(R.id.fab);
pd = new ProgressDialog(getActivity());
Query query = databaseReference.orderByChild("email").equalTo(user.getEmail());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String name = "" + ds.child("name").getValue();
String image = "" + ds.child("image").getValue();
String email = "" + ds.child("email").getValue();
String phone = "" + ds.child("phone").getValue();
String cover = "" + ds.child("cover").getValue();
nameTv.setText(name);
emailTv.setText(email);
phoneTv.setText(phone);
try {
Picasso.get().load(image).into(avatartv);
} catch (Exception e) {
Picasso.get().load(R.drawable.ic_add_a_photo_black_24dp).into(avatartv);
}
try {
Picasso.get().load(cover).into(coverTv);
} catch (Exception e) {
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showEditProfileDialog();
}
});
return view;
}
private boolean checkStoragePermission() {
boolean result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result;
}
private void requestStoragePermission() {
requestPermissions(storagePermission, STORAGE_REQUEST_CODE);
}
private boolean checkCameraPermission() {
boolean result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
== (PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result && result1;
}
private void requestCameraPermission() {
requestPermissions(cameraPermissions, CAMERA_REQUEST_CODE);
}
private void showEditProfileDialog() {
String options[] = {"Edit Profile Picture", "Edit Cover Photo", "Edit Name", "Edit Phone"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose Action");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
pd.setMessage("Updating Profile Picture");
profileOrCoverPhoto = "image";
showImagePicDialog();
} else if (which == 1) {
pd.setMessage("Updating Cover Picture");
profileOrCoverPhoto = "cover";
showImagePicDialog();
} else if (which == 2) {
pd.setMessage("Updating Name");
showNamePhoneUpdateDialog("name");
} else if (which == 3) {
pd.setMessage("Updating Phone");
showNamePhoneUpdateDialog("phone");
}
}
});
builder.create().show();
}
private void showNamePhoneUpdateDialog(String Key) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Updated " + Key);
LinearLayout linearLayout = new LinearLayout(getActivity());
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setPadding(10, 10, 10, 10);
EditText editText = new EditText(getActivity());
editText.setHint("Enter " + Key);
linearLayout.addView(editText);
builder.setView(linearLayout);
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String value = editText.getText().toString().trim();
if (!TextUtils.isEmpty(value)) {
pd.show();
HashMap<String, Object> result = new HashMap<>();
result.put(Key, value);
databaseReference.child(user.getUid()).updateChildren(result)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
pd.dismiss();
Toast.makeText(getActivity(), "Updated...", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(getActivity(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(getActivity(), "Please enter " + Key, Toast.LENGTH_SHORT).show();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
}
private void showImagePicDialog() {
String options[] = {"Camera", "Gallery"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Pick Image From");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
if (!checkCameraPermission()) {
requestCameraPermission();
} else {
pickFromCamera();
}
} else if (which == 1) {
if (!checkStoragePermission()) {
requestStoragePermission();
} else {
pickFromGallery();
}
}
}
});
builder.create().show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case CAMERA_REQUEST_CODE: {
if (grantResults.length > 0) {
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (cameraAccepted && writeStorageAccepted) {
pickFromCamera();
} else {
Toast.makeText(getActivity(), "Please Enable Camera & Storage Permission", Toast.LENGTH_SHORT).show();
}
}
}
break;
case STORAGE_REQUEST_CODE: {
if (grantResults.length > 0) {
boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (writeStorageAccepted) {
pickFromGallery();
} else {
Toast.makeText(getActivity(), "Please Enable Storage Permission", Toast.LENGTH_SHORT).show();
}break;
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_PICK_GALLERY_CODE) {
image_uri = data.getData();
uploadProfileCoverPhoto(image_uri);
}
if (requestCode == IMAGE_PICK_CAMERA_CODE) {
uploadProfileCoverPhoto(image_uri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void uploadProfileCoverPhoto(Uri uri) {
String filePathAndName = storagePath + "" + profileOrCoverPhoto + "_" + user.getUid();
StorageReference storageReference2nd = storageReference.child(filePathAndName);
storageReference2nd.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful()) ;
Uri downloadUri = uriTask.getResult();
if (uriTask.isSuccessful()) {
HashMap<String, Object> results = new HashMap<>();
results.put(profileOrCoverPhoto, downloadUri.toString());
databaseReference.child(user.getUid()).updateChildren(results)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
pd.dismiss();
Toast.makeText(getActivity(), "Image Updated ...", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(getActivity(), "Error Updating Image ...", Toast.LENGTH_SHORT).show();
}
});
} else {
pd.dismiss();
Toast.makeText(getActivity(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void pickFromCamera() {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Temp Pic");
values.put(MediaStore.Images.Media.DESCRIPTION, "Temp Description");
image_uri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE);
}
private void pickFromGallery() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, IMAGE_PICK_GALLERY_CODE);
}
XML Codes:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".ProfileFragment">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/coverTv"
android:layout_width="match_parent"
android:layout_height="180dp"
android:background="#FFA117">
</ImageView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="120dp"
android:layout_marginTop="90dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/avatarTv"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_marginStart="20dp"
android:layout_marginLeft="20dp"
android:background="#color/colorPrimaryDark"
android:scaleType="fitXY"
app:srcCompat="#drawable/face" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#B67310"
android:orientation="vertical">
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:textColor="#fff"
android:textSize="25sp" />
<TextView
android:id="#+id/category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:textColor="#fff"
android:textSize="15dp" />
<TextView
android:id="#+id/location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:textColor="#fff"
android:textSize="15dp" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</ScrollView>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_margin="10dp"
android:src="#drawable/editpen"
app:backgroundTint="#FFA117" />
</RelativeLayout>
FIrebase Security Rules:
service firebase.storage {
match /b/learno-fc8fc.appspot.com/o {
// Allow access by all users
allow read, write;
}
Screenshot of the issue.
Can you please cross check your bucket name if it correct.
After searching i found solution ..
My rules in Firebase was not right ..
we should make it like that ..
service firebase.storage
{ match /b/learno-fc8fc.appspot.com/o
{ match /{allPaths=**}
{ // Allow access by all users
allow read, write; }
I want to send mp3 files to firebase storage but my code is not working. I don't have an error. it just doesn't work.
I want to upload the sound file I selected from my phone to firebase storage.
here is my code:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RQS_OPEN_AUDIO_MP3 && resultCode == Activity.RESULT_OK) {
if ((data != null) && (data.getData() != null)) {
Uri mp3FileUri = data.getData();
Toast.makeText(sesyolla.this, "OKAY", Toast.LENGTH_SHORT).show();
info.setText(mp3FileUri.getPath());
}
}
}
private void uploadFile() {
if (mp3FileUri != null) {
final StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mp3FileUri));
fileReference.putFile(mp3FileUri).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 fileReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
Log.e(TAG, "then: " + downloadUri.toString());
Upload upload = new Upload(edittext.getText().toString().trim(),
downloadUri.toString());
mDatabaseRef.push().setValue(upload);
} else {
Toast.makeText(sesyolla.this, "upload failed: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
Full solution:
CloudStorageDatabaseUtils.java
public class CloudStorageDatabaseUtils {
public void uploadImage(String storageChildAndPath, File file) {
Uri uriFile = Uri.fromFile(file);
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
final StorageReference ref = storageRef.child(storageChildAndPath);
ref.putFile(uriFile);
}
public void getDownloadURL(String path, UrlReceiver receiver) {
StorageReference reference = FirebaseStorage.getInstance().getReference().child(path);
reference.getDownloadUrl().addOnSuccessListener(uri -> receiver.onUrlReceived(uri.toString()));
}
}
activity_upload_image.xml
just a button
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/button_upload"
android:layout_width="100dp"
android:layout_height="100dp"
android:text="#string/action_upload_an_image"/>
</LinearLayout>
UrlReceiver.java
public interface UrlReceiver {
/**
* #param url URL which will be received
*/
void onUrlReceived(String url);
}
UploadImageActivity.java
public class UploadImageActivity extends AppCompatActivity implements View.OnClickListener, UrlReceiver {
CloudStorageDatabaseUtils databaseUtils = new CloudStorageDatabaseUtils();
String downloadUrl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_image);
Button upload = findViewById(R.id.button_upload);
upload.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_upload:
File rootStorage = Environment.getExternalStorageDirectory();
File exactlyFile = new File(rootStorage.toString() + "/download/q1.jpeg");//or whatever
databaseUtils.uploadImage("/example1/" + exactlyFile.getName(), exactlyFile);
databaseUtils.getDownloadURL("/example1/" + exactlyFile.getName(), this);
}
}
#Override
public void onUrlReceived(String url) {
if (url != null) {
downloadUrl = url;
Log.d("MyS", "url: " + url);
}
}
}
Please help me.
I have a problem with displaying image from MYSQL table with the path i get as response.
After login, I want to display user image which path found in the same record in the users table.
My java activity and XML file are :
public class HomeActivity extends AppCompatActivity {
private static final String TAG = HomeActivity.class.getSimpleName(); //getting the info
private TextView name, email,photo;
private Button btn_logout, btn_photo_upload;
SessionManager sessionManager;
String getId;
private static String URL_READ = "http://172.23.50.55/CP/read_detail.php";
private static String URL_EDIT = "http://172.23.50.55/CP/edit_detail.php";
private static String URL_UPLOAD = "http://172.23.50.55/CP/upload.php";
private Menu action;
private Bitmap bitmap;
CircleImageView profile_image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
sessionManager = new SessionManager(this);
sessionManager.checkLogin();
name = findViewById(R.id.name);
email = findViewById(R.id.email);
photo = findViewById(R.id.photo);
btn_logout = findViewById(R.id.btn_logout);
btn_photo_upload = findViewById(R.id.btn_photo);
HashMap<String, String> user = sessionManager.getUserDetail();
getId = user.get(sessionManager.ID);
btn_logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sessionManager.logout();
}
});
btn_photo_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chooseFile();
}
});
}
//getUserDetail
private void getUserDetail(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_READ,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
Log.i(TAG, response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
JSONArray jsonArray = jsonObject.getJSONArray("read");
if (success.equals("1")){
for (int i =0; i < jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
String strName = object.getString("name").trim();
String strEmail = object.getString("email").trim();
// System.out.println("pspspspspspspspspspspspspspsp " + strEmail);
String strPhoto = object.getString("photo").trim();
name.setText(strName);
email.setText(strEmail);
photo.setText(strPhoto);
}
}
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
Toast.makeText(HomeActivity.this, "Error Reading Detail "+e.toString(), Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(HomeActivity.this, "Error Reading Detail "+error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String > params = new HashMap<>();
params.put("id", getId);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
protected void onResume() {
super.onResume();
getUserDetail();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_action, menu);
action = menu;
action.findItem(R.id.menu_save).setVisible(false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_edit:
name.setFocusableInTouchMode(true);
email.setFocusableInTouchMode(true);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(name, InputMethodManager.SHOW_IMPLICIT);
action.findItem(R.id.menu_edit).setVisible(false);
action.findItem(R.id.menu_save).setVisible(true);
return true;
case R.id.menu_save:
SaveEditDetail();
action.findItem(R.id.menu_edit).setVisible(true);
action.findItem(R.id.menu_save).setVisible(false);
name.setFocusableInTouchMode(false);
email.setFocusableInTouchMode(false);
name.setFocusable(false);
email.setFocusable(false);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//save
private void SaveEditDetail() {
final String name = this.name.getText().toString().trim();
final String email = this.email.getText().toString().trim();
final String id = getId;
final String photo = this.photo.getText().toString().trim();
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Saving...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_EDIT,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if (success.equals("1")){
Toast.makeText(HomeActivity.this, "Success!", Toast.LENGTH_SHORT).show();
System.out.println("popopopopopopopopopopo");
sessionManager.createSession(name, email, id, photo);
}
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
Toast.makeText(HomeActivity.this, "Error "+ e.toString(), Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(HomeActivity.this, "Error "+ error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("name", name);
params.put("email", email);
params.put("photo",photo);
params.put("id", id);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void chooseFile(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
profile_image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
UploadPicture(getId, getStringImage(bitmap));
}
}
private void UploadPicture(final String id, final String photo) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Uploading...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_UPLOAD,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
Log.i(TAG, response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if (success.equals("1")){
Toast.makeText(HomeActivity.this, "Success!", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
Toast.makeText(HomeActivity.this, "Try Again!"+e.toString(), Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(HomeActivity.this, "Try Again!" + error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("id", id);
params.put("photo", photo);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public String getStringImage(Bitmap bitmap){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] imageByteArray = byteArrayOutputStream.toByteArray();
String encodedImage = Base64.encodeToString(imageByteArray, Base64.DEFAULT);
System.out.println("encodedImage " + encodedImage);
return encodedImage;
}
}
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HomeActivity">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/photo"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
/>
<Button
android:id="#+id/btn_photo"
style="#style/Widget.AppCompat.ActionButton.CloseMode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/photo"
android:layout_centerHorizontal="true"
android:text="Edit Photo" />
<LinearLayout
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_below="#id/btn_photo"
android:weightSum="2"
android:id="#+id/layout_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:src="#drawable/ic_name"
android:layout_weight="1"
android:layout_width="70dp"
android:layout_height="50dp" />
<EditText
android:id="#+id/name"
android:hint="Name"
android:inputType="textPersonName"
android:layout_marginLeft="10dp"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_below="#id/layout_text"
android:weightSum="2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:src="#drawable/ic_email"
android:layout_weight="1"
android:layout_width="70dp"
android:layout_height="50dp" />
<EditText
android:id="#+id/email"
android:hint="Email"
android:inputType="textPersonName"
android:layout_marginLeft="10dp"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<Button
android:layout_alignParentBottom="true"
android:id="#+id/btn_logout"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginBottom="30dp"
android:textColor="#android:color/white"
android:backgroundTint="#color/colorPrimary"
android:text="Logout"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
Please any one can help me in details.
I used android studio and xamp server.
The table contain: id, name, email,password, photo(path)
In the onActivityResult event, you already get the image URI. Use the setImageURI method.
Uri filePath = data.getData();
imageView.setImageURI(uri);