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>
Related
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);
}
});
}
Hi I want to add an image on firebase storage with android studio but firebase doesn't accept my upload. I changed the rule to allow the write and read and my match folder allows all path.Thus I am confused. Here is the part of my code who should put the image in my database.
If you know how to resolve this problem i would be glad to ear a solution
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE){
image_uri = data.getData();
uploadPicture();
ProfileImage.setImageURI(image_uri);
}
}
private void uploadPicture() {
final ProgressDialog pd = new ProgressDialog(this);
pd.setTitle("Uploading Image...");
pd.show();
final String randomKey = UUID.randomUUID().toString();
StorageReference riversRef = storageReference.child(("images/" + randomKey + ".jpg"));
Toast.makeText(Create_Profile.this, "Upload success", Toast.LENGTH_SHORT).show();
riversRef.putFile(image_uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
pd.dismiss();
name = riversRef.getDownloadUrl().toString();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
double progressPercent = (100.00 * snapshot.getBytesTransferred() / snapshot.getTotalByteCount());
pd.setMessage("Percentage: " + (int) progressPercent + "%");
}
});
}
if you don't getting error compare with this simple code
thank you
firebase storage dependency
implementation 'com.google.firebase:firebase-storage:19.1.0'
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">
<!--Linear Layout with horizontal orientation
and other properties-->
<LinearLayout
android:id="#+id/layout_button"
android:orientation="horizontal"
android:layout_alignParentTop="true"
android:weightSum="2"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!--Button for choosing image from gallery-->
<Button
android:id="#+id/btnChoose"
android:text="Choose"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<!--Button for uploading image-->
<Button
android:id="#+id/btnUpload"
android:text="Upload"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
</LinearLayout>
<!--Image View for showing image choosen from gallery-->
<ImageView
android:id="#+id/imgView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
in your Activity
public class MainActivity extends AppCompatActivity {
private Button btnSelect, btnUpload;
private ImageView imageView;
private Uri filePath;
private final int PICK_IMAGE_REQUEST = 22;
FirebaseStorage storage;
StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar;
actionBar = getSupportActionBar();
ColorDrawable colorDrawable
= new ColorDrawable(
Color.parseColor("#0F9D58"));
actionBar.setBackgroundDrawable(colorDrawable);
btnSelect = findViewById(R.id.btnChoose);
btnUpload = findViewById(R.id.btnUpload);
imageView = findViewById(R.id.imgView);
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
SelectImage();
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
uploadImage();
}
});
}
private void SelectImage()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(
intent,
"Select Image from here..."),
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) {
// Get the Uri of data
filePath = data.getData();
try {
Bitmap bitmap = MediaStore
.Images
.Media
.getBitmap(
getContentResolver(),
filePath);
imageView.setImageBitmap(bitmap);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
private void uploadImage()
{
if (filePath != null) {
ProgressDialog progressDialog
= new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference ref
= storageReference
.child(
"images/"
+ UUID.randomUUID().toString());
ref.putFile(filePath)
.addOnSuccessListener(
new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(
UploadTask.TaskSnapshot taskSnapshot)
{
progressDialog.dismiss();
Toast
.makeText(MainActivity.this,
"Image Uploaded!!",
Toast.LENGTH_SHORT)
.show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e)
{
progressDialog.dismiss();
Toast
.makeText(MainActivity.this,
"Failed " + 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());
progressDialog.setMessage(
"Uploaded "
+ (int)progress + "%");
}
});
}
}
}
I found a solution by modifying my firebase Rules to match with the bucket directly and not with the ref of my firebase storage
I have an audiobook app that I'm currently working on. If the book has audio, the controller will be shown. If not, it'll only show the text. I want to switch the chapters just by swiping at the text. I'm currently using a RelativeLayout and the text is wrapped in a ScrollView. I read that I should use ViewPager. But I was wondering if I could just keep using the RelativeLayout and ScrollView.
player.xml:
<?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"
android:background="#drawable/mainbg">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/m_tab_color"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<LinearLayout
android:id="#+id/player_footer_bg"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#FFFFFF"
android:gravity="center"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/linearButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp">
<ImageButton
android:id="#+id/btnRepeat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:background="#null"
android:src="#drawable/btn_repeat"
tools:ignore="ContentDescription" />
<ImageButton
android:id="#+id/btnShuffle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:background="#null"
android:src="#drawable/btn_shuffle"
tools:ignore="ContentDescription" />
<ImageButton
android:id="#+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerVertical="true"
android:layout_toEndOf="#+id/btnPlay"
android:background="#null"
android:src="#drawable/btn_next"
tools:ignore="ContentDescription" />
<ImageButton
android:id="#+id/btnPlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_margin="5dp"
android:background="#drawable/btn_play"
android:src="#drawable/pause"
tools:ignore="ContentDescription" />
<ImageButton
android:id="#+id/btnPrevious"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toStartOf="#+id/btnPlay"
android:background="#null"
android:src="#drawable/btn_prev"
tools:ignore="ContentDescription" />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<FrameLayout
android:id="#+id/ad_view_container"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<RelativeLayout
android:id="#+id/ads_startapp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone">
</RelativeLayout>
</LinearLayout>
</LinearLayout>
<RelativeLayout
android:id="#+id/sec_ssekbar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/player_footer_bg"
android:layout_centerVertical="true"
android:background="#00ffffff"
android:paddingLeft="7dp"
android:paddingRight="7dp">
<SeekBar
android:id="#+id/songProgressBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:progressTint="#E94C3D"
android:thumb="#drawable/pointer"
android:thumbTint="#E94C3D"
android:thumbOffset="8dp"/>
<TextView
android:id="#+id/songCurrentDurationLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/songProgressBar"
android:gravity="start"
android:text="#string/current_duration"
android:textColor="#color/black"
android:textStyle="bold" />
<TextView
android:id="#+id/songTotalDurationLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="#+id/songProgressBar"
android:gravity="end"
android:text="#string/total_duration"
android:textColor="#color/black"
android:textStyle="bold" />
</RelativeLayout>
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/sec_ssekbar"
android:layout_below="#+id/toolbar"
android:layout_centerInParent="true"
android:layout_marginStart="3dp"
android:layout_marginTop="3dp"
android:layout_marginEnd="3dp"
android:layout_marginBottom="3dp"
android:background="#B3FFFFFF">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/text_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginTop="3dp"
android:layout_marginEnd="5dp"
android:layout_marginBottom="3dp"
android:gravity="center"
android:text="#string/app_name"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/black"
android:textStyle="bold" />
<TextView
android:id="#+id/text_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="5dp"
android:layout_marginBottom="5dp"
android:text="#string/app_name"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/black" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
MusicPlayActivity.java
public class MusicPlayActivity extends AppCompatActivity implements OnCompletionListener, SeekBar.OnSeekBarChangeListener {
Toolbar toolbar;
private ImageButton btnPlay;
private ImageButton btnRepeat;
private ImageButton btnShuffle;
private MediaPlayer mp;
ImageView img_song;
private int currentSongIndex = 0;
private boolean isShuffle = false;
private boolean isRepeat = false;
String[] allArrayImage, allArrayMusicCatName, allArrayMusicShare;
String[] allArrayMusicId, allArrayMusicCatId, allArrayMusicurl, allArrayMusicName, allArrayMusicDuration, allArrayMusicDesc;
int position = currentSongIndex;
int music_id;
private SeekBar songProgressBar;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
private Utilities utils;
private Handler mHandler = new Handler();
private Menu menu;
DatabaseHandler db;
String mp3id, mp3catid, mp3name, mp3url, mp3duration, mp3desc, mp3shareurl, mp3image, mp3catname;
private ActionClickItem actionClickItem;
private InterstitialAd mInterstitialAd;
private int btNextClicked = 1;
private AdsObj adsObj;
private StartAppAd startAppAd;
private boolean runClickExecuted;
private AdView adView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {}
});
btnPlay = findViewById(R.id.btnPlay);
ImageButton btnNext = findViewById(R.id.btnNext);
ImageButton btnPrevious = findViewById(R.id.btnPrevious);
btnRepeat = findViewById(R.id.btnRepeat);
btnShuffle = findViewById(R.id.btnShuffle);
TextView songTitleLabel = findViewById(R.id.text_title);
TextView songDesc = findViewById(R.id.text_description);
img_song = findViewById(R.id.image);
songProgressBar = findViewById(R.id.songProgressBar);
songCurrentDurationLabel = findViewById(R.id.songCurrentDurationLabel);
songTotalDurationLabel = findViewById(R.id.songTotalDurationLabel);
//imageView = (ImageView)findViewById(R.id.full_image);
// imageLoader=new ImageLoader(this);
db = new DatabaseHandler(this);
toolbar = this.findViewById(R.id.toolbar);
toolbar.setTitle(Constant.MUSIC_NAME);
this.setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
utils = new Utilities();
mp = new MediaPlayer();
Intent i = getIntent();
music_id = i.getIntExtra("POSITION", 0);
allArrayImage = i.getStringArrayExtra("MP3_IMAGE");
allArrayMusicCatName = i.getStringArrayExtra("MP3_CATNAME");
allArrayMusicShare = i.getStringArrayExtra("MP3_SHARE");
allArrayMusicId = i.getStringArrayExtra("MP3_CID");
allArrayMusicCatId = i.getStringArrayExtra("MP3_CATID");
allArrayMusicurl = i.getStringArrayExtra("MP3_URL");
allArrayMusicName = i.getStringArrayExtra("MP3_NAME");
allArrayMusicDuration = i.getStringArrayExtra("MP3_DURATION");
allArrayMusicDesc = i.getStringArrayExtra("MP3_DISCRIPTION");
position = getPositionFromArray(String.valueOf(music_id));
Log.e("POSITIO", "" + position);
playSong(position);
songProgressBar.setOnSeekBarChangeListener(this);
mp.setOnCompletionListener(this);
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// check for already playing
if (mp.isPlaying()) {
if (mp != null) {
mp.pause();
// Changing button image to play button
btnPlay.setImageResource(R.drawable.btn_play);
}
} else {
// Resume song
if (mp != null) {
mp.start();
// Changing button image to pause button
btnPlay.setImageResource(R.drawable.btn_paush);
}
}
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
btNextClicked++;
if ((btNextClicked % 3 == 0)) {
actionItemClicked(new ActionClickItem() {
#Override
public void runClick() {
// check if next song is there or not
if (position < (allArrayMusicurl.length - 1)) {
playSong(position + 1);
position = position + 1;
} else {
// play first song
playSong(0);
position = 0;
}
}
});
} else {
// check if next song is there or not
if (position < (allArrayMusicurl.length - 1)) {
position = position + 1;
playSong(position + 1);
} else {
// play first song
playSong(0);
position = 0;
}
}
}
});
btnPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (position > 0) {
playSong(position - 1);
position = position - 1;
} else {
// play last song
playSong(allArrayMusicurl.length - 1);
position = allArrayMusicurl.length - 1;
}
}
});
btnRepeat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (isRepeat) {
isRepeat = false;
Toast.makeText(getApplicationContext(), "Repeat is OFF", Toast.LENGTH_SHORT).show();
btnRepeat.setImageResource(R.drawable.btn_repeat);
} else {
// make repeat to true
isRepeat = true;
Toast.makeText(getApplicationContext(), "Repeat is ON", Toast.LENGTH_SHORT).show();
// make shuffle to false
isShuffle = false;
btnRepeat.setImageResource(R.drawable.btn_repeat_focused);
btnShuffle.setImageResource(R.drawable.btn_shuffle);
}
}
});
btnShuffle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (isShuffle) {
isShuffle = false;
Toast.makeText(getApplicationContext(), "Shuffle is OFF", Toast.LENGTH_SHORT).show();
btnShuffle.setImageResource(R.drawable.btn_shuffle);
} else {
// make repeat to true
isShuffle = true;
Toast.makeText(getApplicationContext(), "Shuffle is ON", Toast.LENGTH_SHORT).show();
// make shuffle to false
isRepeat = false;
btnShuffle.setImageResource(R.drawable.btn_shuffle_focused);
btnRepeat.setImageResource(R.drawable.btn_repeat);
}
}
});
//int songIndex = i.getIntExtra("songIndex", 0);
// Displaying Song title
String songTitle = allArrayMusicName[position];
songTitleLabel.setText(songTitle);
toolbar.setTitle(songTitle);
String musicUrl = allArrayMusicurl[position];
if(musicUrl.equals(".")){
songProgressBar.setVisibility(View.GONE);
songCurrentDurationLabel.setVisibility(View.GONE);
songTotalDurationLabel.setVisibility(View.GONE);
RelativeLayout linearButton = findViewById(R.id.linearButton);
linearButton.setVisibility(View.GONE);
}
#SuppressLint("CutPasteId") FrameLayout frameAds1 = findViewById(R.id.ad_view_container);
AdsAssistants adsAssistants = new AdsAssistants(this);
adsObj = adsAssistants.getSessionAdsObj();
if (adsObj != null) {
if (adsObj.getCurrentActivatedAds().equals(AdsConfig.ADS_ADMOB)) {
frameAds1.setVisibility(View.VISIBLE);
adsAssistants.createAdmobBanner(frameAds1, adsObj.getADS_ADMOB_BANNER());
} else {
startAppAd = new StartAppAd(this);
#SuppressLint("CutPasteId") FrameLayout frameAds = findViewById(R.id.ad_view_container);
frameAds.setVisibility(View.VISIBLE);
adsAssistants.createStartAppBanner(frameAds);
}
}
}
public void actionItemClicked(ActionClickItem actionClickItemParam) {
actionClickItem = actionClickItemParam;
if (adsObj == null) {
actionClickItem.runClick();
} else {
if (adsObj.getCurrentActivatedAds().equals(AdsConfig.ADS_ADMOB)) {
if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
actionClickItem.runClick();
generateInterstitialAd();
}
} else {
startAppAd.loadAd(new AdEventListener() {
#Override
public void onReceiveAd(Ad ad) {
}
#Override
public void onFailedToReceiveAd(Ad ad) {
// actionClickItem.runClick();
}
});
StartAppAd.disableAutoInterstitial();
startAppAd.showAd(new AdDisplayListener() {
#Override
public void adHidden(Ad ad) {
if(!runClickExecuted){
runClickExecuted = true;
actionClickItem.runClick();
}
Log.d("YWV", "Action clicked");
}
#Override
public void adDisplayed(Ad ad) {
}
#Override
public void adClicked(Ad ad) {
}
#Override
public void adNotDisplayed(Ad ad) {
}
});
}
}
}
private void generateInterstitialAd() {
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(adsObj.getADS_ADMOB_INTERSTITIALS());
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
// mNextLevelButton.setEnabled(true);
}
#Override
public void onAdFailedToLoad(int errorCode) {
// mNextLevelButton.setEnabled(true);
}
#Override
public void onAdClosed() {
// Proceed to the next level.
//finish();
//showDialogApp();
actionClickItem.runClick();
generateInterstitialAd();
}
});
AdRequest adRequestIn = new AdRequest.Builder().build();
mInterstitialAd.loadAd(adRequestIn);
}
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
position = Objects.requireNonNull(data.getExtras()).getInt("songIndex");
// play selected song
playSong(position);
}else if(resultCode == 11){
runClickExecuted = false;
}
}
public void playSong(int songIndex) {
// Play song
try {
// if(needResetFirst){
mp.reset();
// }
mp.setDataSource(allArrayMusicurl[songIndex]);
mp.prepare();
mp.start();
// // Displaying Song title
TextView songTitleLabel = findViewById(R.id.text_title);
String songTitle = allArrayMusicName[songIndex];
songTitleLabel.setText(songTitle);
toolbar.setTitle(songTitle);
TextView songDesc = findViewById(R.id.text_description);
String songDescd = allArrayMusicDesc[songIndex];
songDesc.setText(songDescd);
// Toast.makeText(getApplicationContext(), img_name,Toast.LENGTH_SHORT).show();
// imageLoader.DisplayImage(Constant.SERVER_IMAGE_UPFOLDER1+img_name, imageView);
// Log.e("IMAGEPATH", ""+Constant.SERVER_IMAGE_UPFOLDER1+img_name);
// Toast.makeText(getApplicationContext(), Constant.SERVER_IMAGE_UPFOLDER1+img_name,Toast.LENGTH_SHORT).show();
// Changing Button Image to pause image
btnPlay.setImageResource(R.drawable.btn_paush);
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
// Updating progress bar
updateProgressBar();
// set Progress bar values
} catch (IllegalArgumentException | IllegalStateException | IOException e) {
e.printStackTrace();
}
}
#Override
public void onCompletion(MediaPlayer arg0) {
// check for repeat is ON or OFF
if (isRepeat) {
// repeat is on play same song again
playSong(position);
} else if (isShuffle) {
// shuffle is on - play a random song
Random rand = new Random();
position = rand.nextInt((allArrayMusicurl.length - 1) + 1);
playSong(position);
} else {
// no repeat or shuffle ON - play next song
if (position < (allArrayMusicurl.length - 1)) {
playSong(position + 1);
position = position + 1;
} else {
// play first song
playSong(0);
position = 0;
}
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
if (mp != null) {
mp.reset();
mp.release();
mp = null;
mHandler.removeCallbacks(mUpdateTimeTask);
}
setResult(RESULT_OK);
finish();
}
public void updateProgressBar() {
mHandler.postDelayed(mUpdateTimeTask, 100);
}
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
// Displaying Total Duration time
songTotalDurationLabel.setText(utils.milliSecondsToTimer(totalDuration));
// Displaying time completed playing
songCurrentDurationLabel.setText(utils.milliSecondsToTimer(currentDuration));
// Updating progress bar
int progress = utils.getProgressPercentage(currentDuration, totalDuration);
//Log.d("Progress", ""+progress);
songProgressBar.setProgress(progress);
// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100);
}
};
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// remove message Handler from updating progress bar
mHandler.removeCallbacks(mUpdateTimeTask);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTimeTask);
int totalDuration = mp.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);
// forward or backward to certain seconds
mp.seekTo(currentPosition);
// update timer progress again
updateProgressBar();
}
public void AddtoFav(int position) {
mp3id = allArrayMusicId[position];
// mp3catid=allArrayMusicCatId[position];
mp3catname = allArrayMusicCatName[position];
mp3url = allArrayMusicurl[position];
mp3image = allArrayImage[position];
mp3name = allArrayMusicName[position];
mp3duration = allArrayMusicDuration[position];
mp3desc = allArrayMusicDesc[position];
// mp3shareurl=allArrayMusicShare[position];
db.AddtoFavorite(new Pojo(mp3id, mp3catid, mp3catname, mp3url, mp3image, mp3name, mp3duration, mp3desc, mp3shareurl));
Toast.makeText(getApplicationContext(), "Added to Favorite", Toast.LENGTH_SHORT).show();
// fabfav.setImageDrawable(getResources().getDrawable(R.drawable.fav_hover));
}
//remove from favorite
public void RemoveFav(int position) {
mp3id = allArrayMusicId[position];
db.RemoveFav(new Pojo(mp3id));
Toast.makeText(getApplicationContext(), "Removed from Favorite", Toast.LENGTH_SHORT).show();
// fabfav.setImageDrawable(getResources().getDrawable(R.drawable.fav_hover));
}
public void FirstFav() {
mp3id = allArrayMusicId[position];
List<Pojo> pojolist = db.getFavRow(mp3id);
if (pojolist.size() == 0) {
menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.fav));
} else {
if (pojolist.get(0).getMp3Id().equals(mp3id)) {
menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.fav_hover));
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_mp3, menu);
this.menu = menu;
//for when 1st item of view pager is favorite mode
FirstFav();
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.menu_fav:
mp3id = allArrayMusicId[position];
List<Pojo> pojolist = db.getFavRow(mp3id);
if (pojolist.size() == 0) {
AddtoFav(position);//if size is zero i.e means that record not in database show add to favorite
menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.fav_hover));
} else {
if (pojolist.get(0).getMp3Id().equals(mp3id)) {
RemoveFav(position);
}
menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.fav));
}
return true;
case R.id.menu_share:
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.putExtra(Intent.EXTRA_TEXT, "Listen to this verse from " + Constant.APP_NAME + "\n" + "http://play.google.com/store/apps/details?id=" + getPackageName());
sharingIntent.setType("text/plain");
startActivity(Intent.createChooser(sharingIntent, "Share Link"));
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
public int getPositionFromArray(String id) {
return Arrays.asList(allArrayMusicId).indexOf(id);
}
#Override
public void onResume() {
super.onResume();
if (adView != null) {
adView.resume();
}
}
/** Called when leaving the activity */
#Override
public void onPause() {
if (adView != null) {
adView.pause();
}
super.onPause();
}
/** Called before the activity is destroyed */
#Override
public void onDestroy() {
super.onDestroy();
if (mp != null) {
mp.reset();
mp.release();
mHandler.removeCallbacks(mUpdateTimeTask);
mp = null;
}
finish();
if (adView != null) {
adView.destroy();
}
}
}
Thank you in advance !
You can detect gestures on any View by attaching an onTouchListener to it.
In your case however, you are trying to detect swiping gestures, therefore the best solution is to create a gesture detector class by extending an onTouchListener like in this tutorial (step 4):
https://www.tutorialspoint.com/how-to-handle-right-to-left-and-left-to-right-swipe-gestures-on-android
After doing this, you can easily attach the swipe-detector class to any of your views as:
textView.setOnTouchListener(new OnSwipeTouchListener(MainActivity.this) {
#Override
public void onSwipeLeft() {
super.onSwipeLeft();
// do something
}
#Override
public void onSwipeRight() {
super.onSwipeRight();
// do something
}
});
Have you tried to add and OnSwipeTouchListener like here https://stackoverflow.com/a/12938787/4330467?
Relativelayout should not be the issue
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; }
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);