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.
Related
I am building a survey app and trying to save and listen to the changes of radioButton and store the response as a String. The text of radioButton represents the result of the user's response. I am currently working on storing two strings from the radio buttons. I will expand the concept as I have some survey questions that have four choices for the user to choose from and I want to store and listen to the corresponding strings as well.
I got help from Alex earlier to store as a Boolean. I tried to follow the suggestion to store the correct response as a string. The problem I have is that the string response yes only saved once and does not listen and update the response when the user select no and go back to yes again.
Below are the codes I am working on:
Global:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference uidRef = db.collection("users").document(uid);
RadioGroup radioGroup;
RadioButton yesButton;
RadioButton noButton;
For the OnCreate,
yesButton = findViewById(R.id.a1);
noButton = findViewById(R.id.a2);
radioGroup = findViewById(R.id.radioGroup);
String yes = yesButton.getText().toString();
String no = yesButton.getText().toString();
addSnapshotListener to listen the changes
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()) {
String participate = snapshot.getString("Would you like to participate");
if (participate != null) {
yesButton.setChecked(true);
} else {
noButton.setChecked(true);
}
}
}
});
The two radio buttons:
yesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (yesButton.isChecked()) {
Map<String, Object> update = new HashMap<>();
update.put("Would like to participate", yes);
uidRef.update(update).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(getApplicationContext(), "Response updated ", Toast.LENGTH_SHORT).show();
}
});
}
}
});
noButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (noButton.isChecked()) {
Map<String, Object> update = new HashMap<>();
update.put("Would like to participate", no);
uidRef.update(update).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(getApplicationContext(), "Response updated ", Toast.LENGTH_SHORT).show();
}
});
}
}
});
Firestore structure:
Firestore-root
|
--- users
|
--- userid
|
--- Would you like to participate: yes (//this string does not update)
Added Firestore screenshot (response stored once under the user UID):
The problem I have is that the string response yes only saved once and does not listen and update the response when the user select no and go back to yes again.
You're getting this behavior because you're using the text of the same button:
String yes = yesButton.getText().toString();
String no = yesButton.getText().toString();
See? You're using the yesButton twice. To solve this, change the second line to:
String no = noButton.getText().toString();
// 👆
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);
}
});
}
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 am using this library - https://github.com/stepstone-tech/android-material-stepper to build a step by step registration system where users will fill each field one by one before finally saving users data into the database using a php script via JSON.
I have 2 problems.
1. After filling the data, I dont kow how to save the data that has been inputed into the database.
2 How to validate each data been inputed individually onClick of 'NEXT' button. (Although, number 1 is much more important for now, but if someome could help me out with both, GREAT!.)
I have done this with the use of just one activity and it works fine.
One of the fragment. 6 of them (They are all similar)
public class EmailRegisterFragment extends Fragment implements Step {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_email_register, container, false);
//initialize your UI
return v;
}
#Override
public VerificationError verifyStep() {
//return null if the user can go to the next step, create a new VerificationError instance otherwise
return null;
}
#Override
public void onSelected() {
//update UI when selected
}
#Override
public void onError(#NonNull VerificationError error) {
//handle error inside of the fragment, e.g. show error on EditText
}
}
One of the fragementLayout (They are all similar)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".UsernameRegisterFragment"
android:orientation="vertical">
<!-- TODO: Update blank fragment layout -->
<ImageView
android:layout_width="30dp"
android:layout_height="wrap_content"
android:src="#drawable/back_left_light"
android:layout_marginLeft="10dp"
android:clickable="true"
android:focusable="true"
android:onClick="goToWelcomePage"
android:layout_marginTop="20dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Your Email Address"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginTop="10dp"
android:padding="20dp"
/>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/EditTextTheme"
>
<EditText
android:layout_width="match_parent"
android:inputType="textEmailAddress"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:hint="Input Your Email"
android:textColor="#android:color/black"
android:id="#+id/email"
app:backgroundTint="#color/edit_text"
android:theme="#style/EditTextTheme"
android:textCursorDrawable="#null"
/>
</com.google.android.material.textfield.TextInputLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginTop="20dp"
android:onClick="goToRegisterWithPhone"
android:clickable="true"
android:text="You dont have an email? Click here"/>
</LinearLayout>
Activity layout (That shows the NEXT, BACK COMPLETE Button and progress bar)
<?xml version="1.0" encoding="utf-8"?>
<com.stepstone.stepper.StepperLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/stepperLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:ms_stepperType="progress_bar"
app:ms_nextButtonColor="#color/white"
app:ms_completeButtonColor="#color/white"
app:ms_backButtonColor="#color/white"
/>
ActivityJava file
public class IntroActivity extends AppCompatActivity implements StepperLayout.StepperListener{
private StepperLayout mStepperLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
//remove action and status bar
if (getSupportActionBar() != null)
getSupportActionBar().hide();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intro);
mStepperLayout = (StepperLayout) findViewById(R.id.stepperLayout);
mStepperLayout.setAdapter(new MyStepperAdapter(getSupportFragmentManager(), this));
mStepperLayout.setListener(this);
}
#Override
public void onCompleted(View completeButton) {
Toast.makeText(this, "onCompleted!", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(VerificationError verificationError) {
Toast.makeText(this, "onError! -> " + verificationError.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
#Override
public void onStepSelected(int newStepPosition) {
}
#Override
public void onReturn() {
finish();
}
public void goToWelcomePage(View view){
Intent intent = new Intent(this, WelcomeActivity.class);
startActivity(intent);
}
public void goToRegisterWithPhone(View view){
Intent intent = new Intent(this, IntroActivity.class);
startActivity(intent);
}
}
Like I said I have done this with the use of just one Activity using the Volley library. Check it out.
RegisterActivity.java
public class RegisterActivity extends AppCompatActivity {
private EditText username, email, password;
private Button btn_register_final;
private ProgressBar loading;
private TextView login_text;
private static String URL_REGISTER = "http://78d24f21.ngrok.io/misnap/register.php";
SessionManager sessionManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
sessionManager = new SessionManager(this);
username = findViewById(R.id.etUsername);
email = findViewById(R.id.etEmail);
password = findViewById(R.id.etPassword);
btn_register_final = findViewById(R.id.btnRegisterFinal);
loading = findViewById(R.id.loading);
login_text = findViewById(R.id.btnLoginText);
btn_register_final.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something here after clicking register
Register();
}
});
login_text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
v.getContext().startActivity(intent);
}
});
}
public void Register(){
loading.setVisibility(View.VISIBLE);
btn_register_final.setVisibility(View.GONE);
final String username = this.username.getText().toString().trim();
final String email = this.email.getText().toString().trim();
final String password = this.password.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGISTER,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if(success.equals("1")){
sessionManager.createSession(username, email);
Intent intent = new Intent(RegisterActivity.this, HomeActivity.class);
intent.putExtra("username", username);
intent.putExtra("email", email);
startActivity(intent);
loading.setVisibility(View.GONE);
btn_register_final.setVisibility(View.VISIBLE);
}
} catch (JSONException e){
e.printStackTrace();
Toast.makeText(RegisterActivity.this, "Unable to register" + e.toString(),
Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_register_final.setVisibility(View.VISIBLE);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(RegisterActivity.this, "Unable to register" + error.toString(),
Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_register_final.setVisibility(View.VISIBLE);
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("email", email);
params.put("password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Register.php
<?php
require_once("connect.php");
if ($_SERVER['REQUEST_METHOD']=='POST'){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password = password_hash($password, PASSWORD_DEFAULT);
$sql = "INSERT INTO users (username, email, password)
VALUES ('$username', '$email', '$password')";
if(mysqli_query($conn, $sql)){
$result["success"] = "1";
$result["message"] = "success";
echo json_encode($result);
mysqli_close($conn);
}
else{
$result["success"] = "0";
$result["message"] = "An error occured";
echo json_encode($result);
mysqli_close($conn);
}
}
?>
How do use this same logic for the fragments??
this might be late but i think it would help to others. So for sure you can validate/Insert or whatever you want to do with your inputs on Next button click before going to next step, This is how you can do it in Kotlin
// To be somewhere inside your Step
override fun verifyStep(): VerificationError? {
if (validateStep()){
return null
}
else
VerificationError("Any error message")
}
Now here validateStep will be a function that returns True or false depending upon your needs. Here is a simple example of a validateStep() function. Here you can do anything like insertion or validation etc.
private fun validateStep(): Boolean {
var isValid = true
val name = binding.etCustomerName.text.toString()
val email = binding.etCustomerEmail.text.toString()
if (name.isEmpty()) {
isValid = false
}
if (email.isEmpty()) {
isValid = false
} else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
isValid = false
}
return isValid
}
Do let me know if it helps anyone. Happy coding :)
I am trying to build a simple chat app with a tutorial I followed. I would like to implement some code that when you view all your current chat partners and somebody sends you a new message, that that message style goes into bold until I read it and after that goes back to normal. Now I only know you can change the style in the xml file. But by doing that it changes for all the messages. I want it only for a new incoming unread message. Any advice?
What I have now: https://imgur.com/a/sUeMTK2
What I want: https://imgur.com/a/3YkBDzI
//check for last message
private void lastMessage(final String userid, final TextView last_msg){
theLastMessage = "default";
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Chat chat = snapshot.getValue(Chat.class);
if (firebaseUser != null && chat != null) {
if (chat.getReceiver().equals(firebaseUser.getUid()) && chat.getSender().equals(userid) ||
chat.getReceiver().equals(userid) && chat.getSender().equals(firebaseUser.getUid())) {
theLastMessage = chat.getMessage();
}
}
}
switch (theLastMessage){
case "default":
last_msg.setText("No Message");
break;
default:
last_msg.setText(theLastMessage);
break;
}
theLastMessage = "default";
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
//XML FILE:
<TextView
android:id="#+id/last_msg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/username"
android:layout_marginLeft="20dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="#id/profile_image"
android:maxLines="1"
android:paddingTop="5dp"
android:textStyle="bold"
android:textColor="#color/colorPrimaryDark" />
You can do it with HTML using html tag for bold:
String bold= "<b>" + theLastMessage + "</b> ";
last_message.setText(Html.fromHtml(bold));
if (!chat.isIsseen() && firebaseUser.getUid().equals(chat.getReceiver())){
last_msg.setTypeface(null, Typeface.BOLD_ITALIC );
}else {
last_msg.setTypeface(null,Typeface.ITALIC);
}
Add this after this
theLastMessage = chat.getMessage();