I am trying to build a messenger type app. And for this, I have uploaded an image from my phone to firebase. And the image is successfully stored in firebase storage. And I am trying to show the image on my phone. And I use Picasso to retrieve the image from firebase. But my picture isn't showing. But when I add placeholder I can see the default image that is set by a placeholder. How can I solve this problem? My code is given below:
package com.example.whatsapp2;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.io.IOException;
import java.util.HashMap;
import de.hdodenhof.circleimageview.CircleImageView;
public class SettingsActivity extends AppCompatActivity {
private Button UpdateAccountSetting;
private EditText userName, userStatus;
private CircleImageView userProfileImage;
private String currentUserId;
private FirebaseAuth mAuth;
private DatabaseReference RootRef;
private static final int GalleryPick = 1;
private StorageReference UserProfileImagesRef;
private ProgressDialog loadingBar;
private Toolbar SettingsToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
FirebaseApp.initializeApp(this);
mAuth = FirebaseAuth.getInstance();
currentUserId = mAuth.getCurrentUser().getUid();
RootRef = FirebaseDatabase.getInstance().getReference();
UserProfileImagesRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
InitializeFields();
userName.setVisibility(View.INVISIBLE);
UpdateAccountSetting.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UpdateSettings();
}
});
RetrieveUserInfo();
userProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,GalleryPick);
}
});
}
private void RetrieveUserInfo() {
RootRef.child("Users").child(currentUserId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if((dataSnapshot.exists()) && (dataSnapshot.hasChild("name")) && (dataSnapshot.hasChild("image"))){
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveStatus = dataSnapshot.child("status").getValue().toString();
String retrieveProfileImage = dataSnapshot.child("image").getValue().toString();
userName.setText(retrieveUserName);
userStatus.setText(retrieveStatus);
Picasso.get().load(retrieveProfileImage).into(userProfileImage);
//Picasso.get().load(retrieveProfileImage).placeholder(R.drawable.profile_image).resize(100,100).centerCrop().into(userProfileImage);
}
else if((dataSnapshot.exists()) && (dataSnapshot.hasChild("name"))){
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveStatus = dataSnapshot.child("status").getValue().toString();
userName.setText(retrieveUserName);
userStatus.setText(retrieveStatus);
}
else {
userName.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(),"Please set & update your profile information...",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void UpdateSettings() {
String setUserName = userName.getText().toString();
String setStatus = userStatus.getText().toString();
if (TextUtils.isEmpty(setUserName)) {
Toast.makeText(this,"Please write your user name first....",Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(setStatus)) {
Toast.makeText(this,"Please write your status....",Toast.LENGTH_SHORT).show();
}
else {
HashMap<String, Object> profileMap = new HashMap<>();
profileMap.put("uid", currentUserId);
profileMap.put("name", setUserName);
profileMap.put("status", setStatus);
RootRef.child("Users").child(currentUserId).updateChildren(profileMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
SendUserToMainActivity();
Toast.makeText(getApplicationContext(),"Profile Updated Successfully...",Toast.LENGTH_SHORT).show();
}
else {
String message = task.getException().toString();
Toast.makeText(getApplicationContext(),"Error : "+message,Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void InitializeFields() {
UpdateAccountSetting = findViewById(R.id.update_settings_button);
userName = findViewById(R.id.set_user_name);
userStatus =findViewById(R.id.set_profile_status);
userProfileImage = findViewById(R.id.set_profile_image);
loadingBar = new ProgressDialog(this);
SettingsToolbar = findViewById(R.id.settings_toolbar);
setSupportActionBar(SettingsToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setTitle("Account Settings");
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(this,MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GalleryPick && resultCode == RESULT_OK && data != null){
Uri ImageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(this);
//userProfileImage.setImageURI(ImageUri);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK){
loadingBar.setTitle("Set Profile Image");
loadingBar.setMessage("Please wait, your profile image is updating...");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
Uri resultUri = result.getUri();
StorageReference filePath = UserProfileImagesRef.child(currentUserId+".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(),"Profile Image uploaded Successfully...",Toast.LENGTH_SHORT).show();
final String downloadUrl = task.getResult().getMetadata().getReference().getDownloadUrl().toString();
RootRef.child("Users").child(currentUserId).child("image").setValue(downloadUrl).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(),"Image save in Database Successfully...",Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else{
String message = task.getException().toString();
Toast.makeText(getApplicationContext(),"Error:"+message,Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
else{
String message = task.getException().toString();
Toast.makeText(getApplicationContext(),"Error:"+message,Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
}
}
You can resolve this issue by simply adding 1 line of code:
//in this block
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GalleryPick && resultCode == RESULT_OK && data != null ) {
Uri ImageUri = data.getData();
userProfileImage.setImageURI(ImageUri); //add this line
Related
could you help me, before my code worked well, after the splash I would have my form and I would start the session without any problem, but now I don't know what it was that I got this error ... I already tried several solutions from other forums and no I get to fix it.
it literally tells me what the uid is but I don't know how to make it not null
package com.example.medicare;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import com.example.medicare.modelo.Cita;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;
import java.text.DateFormat;
import java.util.Calendar;
import cn.pedant.SweetAlert.SweetAlertDialog;
import de.hdodenhof.circleimageview.CircleImageView;
public class MenuActivity extends AppCompatActivity {
TextView nombreC, nss;
CircleImageView imagenPerfil;
SharedPreferences sp;
DatabaseReference dbdReferencia;
FirebaseUser usuario;
String uid;
NotificationCompat.Builder builder;
String pacienteNombreC, pacienteNss, fechaHoy;
int numeroCitas;
static int token = 0;
String[] numeros = {"uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez"};
public static void setToken(int number)
{
token = number;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
numeroCitas = 0;
sp = getSharedPreferences("Iniciar Sesion", MODE_PRIVATE);
usuario = FirebaseAuth.getInstance().getCurrentUser();
nombreC = findViewById(R.id.nombreCompleto);
nss = findViewById(R.id.nss);
imagenPerfil = findViewById(R.id.imagen_perfil);
uid = usuario.getUid();
Calendar c = Calendar.getInstance();
fechaHoy = DateFormat.getDateInstance(DateFormat.SHORT).format(c.getTime());
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Citas");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
Cita cita = data.getValue(Cita.class);
if (cita.getEmailPaciente().equals(FirebaseAuth.getInstance().getCurrentUser().getEmail()) &&
cita.getestado().equals("Aceptado") &&
cita.getfecha().equals(fechaHoy)
)
numeroCitas++;
}
if (numeroCitas == 1) {
builder = new NotificationCompat.Builder(com.example.medicare.MenuActivity.this)
.setSmallIcon(R.drawable.ic_heart_beats)
.setContentTitle("Cita diaria")
.setContentText("Usted tiene una cita el dia de hoy")
.setAutoCancel(true)
.setColor(Color.parseColor("#33AEB6"))
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_HIGH);
}
if (numeroCitas > 1) {
builder = new NotificationCompat.Builder(com.example.medicare.MenuActivity.this)
.setSmallIcon(R.drawable.ic_heart_beats)
.setContentTitle("Citas diarias")
.setContentText("Usted tiene " + numeros[numeroCitas - 1] + " citas el dia de hoy")
.setAutoCancel(true)
.setColor(Color.parseColor("#33AEB6"))
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_HIGH);
}
if (numeroCitas == 0) {
builder = new NotificationCompat.Builder(com.example.medicare.MenuActivity.this)
.setSmallIcon(R.drawable.ic_heart_beats)
.setContentTitle("Citas diarias")
.setContentText("Usted no tiene citas el dia de hoy")
.setAutoCancel(true)
.setColor(Color.parseColor("#33AEB6"))
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_HIGH);
}
if(token == 0) {
Intent intent = new Intent(com.example.medicare.MenuActivity.this, AsignarCitaActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(com.example.medicare.MenuActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(
Context.NOTIFICATION_SERVICE
);
notificationManager.notify(0, builder.build());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
dbdReferencia = FirebaseDatabase.getInstance().getReference("Pacientes");
dbdReferencia.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//pacienteNombreC = dataSnapshot.child(uid).child("apellidos").getValue(String.class) + " " + dataSnapshot.child(uid).child("nombreC").getValue(String.class);
pacienteNombreC = dataSnapshot.child(uid).child("nombreC").getValue(String.class);
pacienteNss = dataSnapshot.child(uid).child("nss").getValue(String.class);
nombreC.setText(pacienteNombreC);
nss.setText(pacienteNss);
StorageReference storageReference = FirebaseStorage.getInstance().getReference();
StorageReference profileRef = storageReference.child("imagen_perfil").child(FirebaseAuth.getInstance().getCurrentUser().getEmail() + ".jpg");
profileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.get().load(uri).into(imagenPerfil);
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void buscarDoctor(View view) {
Intent intent = new Intent(com.example.medicare.MenuActivity.this, BuscarDoctorEspecialidadActivity.class);
startActivity(intent);
}
public void Citas(View view) {
Intent intent = new Intent(com.example.medicare.MenuActivity.this, AsignarCitaActivity.class);
startActivity(intent);
}
public void perfilInfo(View view) {
Intent intent = new Intent(com.example.medicare.MenuActivity.this, PerfilPacienteInfo.class);
startActivity(intent);
}
public void abrirExpedienteMedico(View view) {
Intent intent = new Intent(com.example.medicare.MenuActivity.this, ExpedienteMedico.class);
startActivity(intent);
}
public void cerrarSesion(View view) {
sp.edit().putBoolean("Sesion cerrada", false).apply();
FirebaseAuth.getInstance().signOut();
finish();
startActivity(new Intent(com.example.medicare.MenuActivity.this, MainActivity.class));
}
#Override
public void onBackPressed() {
SweetAlertDialog dialog = new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE);
dialog.setConfirmText("Si");
dialog.setCancelText("No");
dialog.setContentText("Estas seguro que deseas salir de edicare ?");
dialog.setTitleText("Cerrar Aplicacion");
dialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
finishAffinity();
System.exit(0);
}
});
dialog.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
sweetAlertDialog.cancel();
}
});
dialog.show();
}
public void myDoctors(View view) {
Intent intent = new Intent(com.example.medicare.MenuActivity.this, MisDoctoresActivity.class);
startActivity(intent);
}
}
I want to store my data in realm but it is not working, it show me error when I click on save button where I add toast. There is no error found, but data is not saving.
My MainActivity Class
package com.deitel.realmrecyclerviewspinnerpriority;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.deitel.realmrecyclerviewspinnerpriority.Modelclass.ModelClass;
import io.realm.Realm;
public class MainActivity extends AppCompatActivity {
private static final String TAG="MainActivity";
Realm realm;
EditText text_name;
EditText text_details;
Button btn_save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
realm=Realm.getDefaultInstance();
Realm.init(getApplicationContext());
text_name = findViewById(R.id.text_name);
text_details = findViewById(R.id.text_details);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
savedata(text_name.getText().toString(),text_details.getText().toString());
}
});
}
private void savedata(final String name, final String datails){
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm bgrealm) {
// Number maxid=bgrealm.where(ModelClass.class).max("id");
// int newkey=(maxid==null) ? 1 : maxid.intValue()+1;
ModelClass user = bgrealm.createObject(ModelClass.class);
user.setName(name);
user.setDetails(datails);
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "success", Toast.LENGTH_SHORT).show();
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
});
}
}
Realm Class Where I initilize configutation etc.
package com.deitel.realmrecyclerviewspinnerpriority;
import android.app.Application;
import io.realm.Realm;
import io.realm.RealmConfiguration;
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
Realm.init(this);
RealmConfiguration configuration=new RealmConfiguration.Builder().name("RealmData.realm").build();
Realm.setDefaultConfiguration(configuration);
}
}
Model Class.
package com.deitel.realmrecyclerviewspinnerpriority.Modelclass;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
public class ModelClass extends RealmObject {
#PrimaryKey
private String Name;
private String Details;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getDetails() {
return Details;
}
public void setDetails(String details) {
Details = details;
}
}
I think you are not setting primary key,
Try below approach
private void savedata(final String name, final String datails){
try(Realm mRealm = Realm.getDefaultInstance()){
ModelClass user = new ModelClass();
int newkey=(maxid==null) ? 1 : maxid.intValue()+1;
user.setId(newkey);
user.setName(name);
user.setDetails(datails);
mRealm.executeTransaction(rlm-> {
rlm.insertOrUpdate(user);
});
}
}
insertOrUpdate inserts a new record if PK doesn't exists else update it.
I'm currently working on a settings page for my app and have been trying to obtain the user profile image from the firebase storage. I am able to upload the picture from the storage.
However, the app does not produce the image onto the activity itself. Is there something wrong with my code?
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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/main_chat_toolbar"
android:background="#color/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
</androidx.appcompat.widget.Toolbar>
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/profile_image"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="85dp"
app:civ_border_color="#color/colorPrimary"
android:src="#drawable/pikachu"
app:civ_border_width="2dp" />
<EditText
android:id="#+id/setting_username"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_below="#id/profile_image"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:drawableLeft="#drawable/ic_action_name"
android:hint="Username"
android:inputType="textMultiLine" />
<EditText
android:id="#+id/set_profile_status"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_below="#+id/setting_username"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:drawableLeft="#drawable/ic_user_status"
android:hint="Hey, I'm available now!"
android:inputType="textMultiLine" />
<Button
android:id="#+id/setting_updatebtn"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_below="#id/set_profile_status"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:background="#drawable/btn_rect"
android:text="Update Settings" />
</RelativeLayout>
Java
package com.shiminu1521462c.fyp_2;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.io.File;
import java.util.HashMap;
import de.hdodenhof.circleimageview.CircleImageView;
public class SettingActivity extends AppCompatActivity {
private EditText etUsername, etUserStatus;
private Button changeSettings;
private CircleImageView userProfileImage;
private Toolbar mToolbar;
private String currentUserID;
private FirebaseAuth mAuth;
private DatabaseReference RootRef;
private static final int GalleryPick = 1;
private StorageReference UserProfileImageRef;
private ProgressDialog LoadingBar;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mToolbar = (Toolbar) findViewById(R.id.main_chat_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Settings");
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
RootRef = FirebaseDatabase.getInstance().getReference();
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
InitializeFields();
etUsername.setVisibility(View.INVISIBLE);
changeSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UpdateSettings();
}
});
RetrieveUserInfo();
userProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GalleryPick);
}
});
}
private void InitializeFields() {
changeSettings = (Button) findViewById(R.id.setting_updatebtn);
etUsername = (EditText) findViewById(R.id.setting_username);
etUserStatus = (EditText) findViewById(R.id.set_profile_status);
userProfileImage = (CircleImageView) findViewById(R.id.profile_image);
LoadingBar = new ProgressDialog(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GalleryPick && resultCode == RESULT_OK && data != null) {
Uri ImageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
LoadingBar.setTitle("Set Profile Image");
LoadingBar.setMessage("Please wait while your profile image is uploading...");
LoadingBar.setCanceledOnTouchOutside(false);
LoadingBar.show();
final Uri resultUri = result.getUri();
StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
Toast.makeText(SettingActivity.this, "Profile Image Uploaded Successfully!", Toast.LENGTH_SHORT).show();
final String downloadUrl = task.getResult().getMetadata().getReference().getDownloadUrl().toString();
RootRef.child("Users").child(currentUserID).child("image")
.setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(SettingActivity.this, "Image saved in Database successfully!", Toast.LENGTH_SHORT).show();
LoadingBar.dismiss();
}else{
String message = task.getException().toString();
Toast.makeText(SettingActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
LoadingBar.dismiss();
}
}
});
} else {
String message = task.getException().toString();
Toast.makeText(SettingActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
LoadingBar.dismiss();
}
}
});
}
}
}
private void UpdateSettings() {
String setUsername = etUsername.getText().toString();
String setStatus = etUserStatus.getText().toString();
if (TextUtils.isEmpty(setUsername)) {
Toast.makeText(this, "Please enter your username..", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(setStatus)){
Toast.makeText(this, "Please set a status..", Toast.LENGTH_SHORT).show();
}
else {
HashMap<String, Object> profileMap = new HashMap<>();
profileMap.put("uid", currentUserID);
profileMap.put("name", setUsername);
profileMap.put("status", setStatus);
RootRef.child("Users").child(currentUserID).updateChildren(profileMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
sendUserToDashboardActivity();
Toast.makeText(SettingActivity.this, "Profile updated successfully!", Toast.LENGTH_SHORT).show();
} else {
String message = task.getException().toString();
Toast.makeText(SettingActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void RetrieveUserInfo() {
RootRef.child("Users").child(currentUserID)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if ((dataSnapshot.exists())
&& (dataSnapshot.hasChild("name")
&& (dataSnapshot.hasChild("image")))) {
String retrieveUsername = dataSnapshot.child("name").getValue().toString();
String retrieveStatus = dataSnapshot.child("status").getValue().toString();
String retrieveProfileImage = dataSnapshot.child("image").getValue().toString();
etUsername.setText(retrieveUsername);
etUserStatus.setText(retrieveStatus);
Picasso.get().load(retrieveProfileImage).into(userProfileImage);
} else if ((dataSnapshot.exists())
&& (dataSnapshot.hasChild("name"))) {
String retrieveUsername = dataSnapshot.child("name").getValue().toString();
String retrieveStatus = dataSnapshot.child("status").getValue().toString();
etUsername.setText(retrieveUsername);
etUserStatus.setText(retrieveStatus);
} else {
etUsername.setVisibility(View.VISIBLE);
Toast.makeText(SettingActivity.this, "Please set and update profile information..", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void sendUserToDashboardActivity() {
Intent mainIntent = new Intent(SettingActivity.this, DashboardActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent myIntent = new Intent(getApplicationContext(), DashboardActivity.class);
startActivityForResult(myIntent, 0);
return true;
}
}
Thank you.
Why not load the image using the resultUri?
Uri resultUri = result.getUri();
Glide.with(this).load(new File(resultUri.getPath())).into(imageView);
Do that after image upload is successful.
have you added the internet permission in the manifest file?
<uses-permission android:name="android.permission.INTERNET" />
I finally managed to solve my issue! This is the altered code, hopefully it helps others who need it! :)
final Uri resultUri = result.getUri();
final StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String downloadUrl = uri.toString();
RootRef.child("Users").child(currentUserID).child("image").setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(SettingActivity.this, "Profile image stored to firebase database successfully.", Toast.LENGTH_SHORT).show();
LoadingBar.dismiss();
} else {
String message = task.getException().getMessage();
Toast.makeText(SettingActivity.this, "Error Occurred..." + message, Toast.LENGTH_SHORT).show();
LoadingBar.dismiss();
}
}
});
}
});
}
i have wrriten a code and getting error in
06-30 23:55:00.702 2499-2499/com.example.parthtiwari.trace E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.parthtiwari.trace, PID: 2499
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null
my code is
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.AuthResult;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
private FirebaseAuth fb;
private DatabaseReference databaseReference;
private EditText editTextEmail;
private EditText editTextPassword;
private EditText editTextName, mobile_number,vehicle_number,editTextAddress;
private Button buttonSignup;
private TextView textViewSignin;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fb = FirebaseAuth.getInstance();
if(fb.getCurrentUser() != null){
finish();
startActivity(new Intent(getApplicationContext(),welcome.class));
}
databaseReference = FirebaseDatabase.getInstance().getReference();
editTextAddress = (EditText) findViewById(R.id.Address);
editTextName = (EditText) findViewById(R.id.name);
mobile_number = (EditText) findViewById(R.id.mobile);
vehicle_number = (EditText) findViewById(R.id.vehicle);
editTextEmail = (EditText) findViewById(R.id.Email);
editTextPassword = (EditText) findViewById(R.id.Password);
buttonSignup = (Button) findViewById(R.id.Signup);
textViewSignin = (TextView) findViewById(R.id.Signin);
progressDialog = new ProgressDialog(this);
FirebaseUser user = fb.getCurrentUser();
buttonSignup.setOnClickListener(this);
textViewSignin.setOnClickListener(this);
}
private void registerUser() {
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
if (TextUtils.isEmpty(email)) {
Toast.makeText(this, "Please enter email",
Toast.LENGTH_LONG).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(this, "Please enter password",
Toast.LENGTH_LONG).show();
return;
}
progressDialog.setMessage("Registering Please Wait...");
progressDialog.show();
fb.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Successfully registered", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Registration Error", Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
}
});
saveUserInformation();
}
private void saveUserInformation() {
String name = editTextName.getText().toString().trim();
String mob = mobile_number.getText().toString().trim();
String vehicle = vehicle_number.getText().toString().trim();
String add = editTextAddress.getText().toString().trim();
//creating a userinformation object
userinfo userInformation = new userinfo(name, mob, vehicle, add);
//getting the current logged in user
FirebaseUser user = fb.getCurrentUser();
databaseReference.child(user.getUid()).setValue(userInformation);
//displaying a success toast
Toast.makeText(this, "Information Saved...", Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View view) {
if(view == buttonSignup){
registerUser();
}
if(view == textViewSignin){
startActivity(new Intent(this, login.class));
}
}
}
Try moving saveUserInformation() into your onCompletionListener.
Looks like saveUserInformation() is called before registration is completed.
fb.createUserWithEmailAndPassword(email, password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
saveUserInformation(authResult);
Toast.makeText(MainActivity.this, "Successfully
registered",Toast.LENGTH_LONG).show();
progressDialog.dismiss(); }).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Registration Error",
Toast.LENGTH_LONG).show();
progressDialog.dismiss();
});
and change
saveUserInformation(AuthResult authResult)
authResult.getUid();
i wonder if someone can help me get it to work, i want to change the webview url every time i change a tab in the tabstrip
i am a new developer so any kind of help will be great.
the main code of the pager and tabs
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.astuetz.PagerSlidingTabStrip;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class MainActivity extends ActionBarActivity {
#InjectView(R.id.toolbar)
Toolbar toolbar;
#InjectView(R.id.tabs)
PagerSlidingTabStrip tabs;
#InjectView(R.id.pager)
ViewPager pager;
private MyPagerAdapter adapter;
private Drawable oldBackground = null;
private int currentColor;
private SystemBarTintManager mTintManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
setSupportActionBar(toolbar);
// create our manager instance after the content view is set
mTintManager = new SystemBarTintManager(this);
// enable status bar tint
mTintManager.setStatusBarTintEnabled(true);
adapter = new MyPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
tabs.setViewPager(pager);
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);
pager.setCurrentItem(1);
changeColor(getResources().getColor(R.color.green));
tabs.setOnTabReselectedListener(new PagerSlidingTabStrip.OnTabReselectedListener() {
#Override
public void onTabReselected(int position) {
Toast.makeText(MainActivity.this, "Tab reselected: " + position, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_contact:
QuickContactFragment.newInstance().show(getSupportFragmentManager(), "QuickContactFragment");
return true;
}
return super.onOptionsItemSelected(item);
}
private void changeColor(int newColor) {
tabs.setBackgroundColor(newColor);
mTintManager.setTintColor(newColor);
// change ActionBar color just if an ActionBar is available
Drawable colorDrawable = new ColorDrawable(newColor);
Drawable bottomDrawable = new ColorDrawable(getResources().getColor(android.R.color.transparent));
LayerDrawable ld = new LayerDrawable(new Drawable[]{colorDrawable, bottomDrawable});
if (oldBackground == null) {
getSupportActionBar().setBackgroundDrawable(ld);
} else {
TransitionDrawable td = new TransitionDrawable(new Drawable[]{oldBackground, ld});
getSupportActionBar().setBackgroundDrawable(td);
td.startTransition(200);
}
oldBackground = ld;
currentColor = newColor;
}
public void onColorClicked(View v) {
int color = Color.parseColor(v.getTag().toString());
changeColor(color);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("currentColor", currentColor);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
currentColor = savedInstanceState.getInt("currentColor");
changeColor(currentColor);
}
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = {"Categories", "Home", "Top Paid", "Top Free", "Top Grossing", "Top New Paid",
"Top New Free", "Trending"};
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Fragment getItem(int position) {
return SuperAwesomeCardFragment.newInstance(position);
}
}
}
and the second code of the textview where i want to change it to webview.
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewCompat;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class SuperAwesomeCardFragment extends Fragment {
private static final String ARG_POSITION = "position";
#InjectView(R.id.textView)
TextView textView;
private int position;
public static SuperAwesomeCardFragment newInstance(int position) {
SuperAwesomeCardFragment f = new SuperAwesomeCardFragment();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt(ARG_POSITION);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_card,container,false);
ButterKnife.inject(this, rootView);
ViewCompat.setElevation(rootView,50);
textView.setText("CARD "+position);
return rootView;
}
}
that's all for now, the layouts files are less important, i will deal with it later.
You should setOnPageChangeListener and use webview.loadUrl(url1);
tabsStrip.setOnPageChangeListener(new OnPageChangeListener() {
// This method will be invoked when a new page becomes selected.
#Override
public void onPageSelected(int position) {
switch(position)
{
case 0:
webview.loadUrl(url1);
break;
case 1:
webview.loadUrl(url2);
break;
case 2:
webview.loadUrl(url3);
break;
}
}
// This method will be invoked when the current page is scrolled
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// Code goes here
}
// Called when the scroll state changes:
// SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
#Override
public void onPageScrollStateChanged(int state) {
// Code goes here
}
});