Place image of the firebase storage in nav_header of navegation_drawer

0

Good I have NavegationDrawer that has an image in nav_header

I would like to know how I can replace that image with the image that is in the storage of firebase of a user

I tried to put this in the activity of my navegation drawer but the application stops

public class MenuActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

private ImageView imgperfil;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;

private FirebaseDatabase database;
private DatabaseReference alumnos;
private StorageReference mStorage;

@Override
protected void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(mAuthListener);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_menu);

    mAuth = FirebaseAuth.getInstance();

    imgperfil = (ImageView) findViewById(R.id.imgperfil);
    mStorage = FirebaseStorage.getInstance().getReference();

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    final FragmentManager fragmentManager=getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.content_menu, new InicioFragment()).commit();

----------------------------A partir de aqui--------------------

    mAuthListener=new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            if (firebaseAuth.getCurrentUser() != null){
                mStorage= FirebaseStorage.getInstance().getReference();
                alumnos = FirebaseDatabase.getInstance().getReference().child("Alumnos");
                alumnos.child(firebaseAuth.getCurrentUser().getUid()).addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        String imageUrl=String.valueOf(dataSnapshot.child("Foto_Perfil").getValue());
                        if (URLUtil.isValidUrl(imageUrl)){
                            Picasso.with(MenuActivity.this).load(Uri.parse(imageUrl)).into(imgperfil);
                        }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });
            }else {
                startActivity(new Intent(MenuActivity.this, IniciaSesionActivity.class));
                finish();
            }
        }
    };
-------------------------Hasta aquí----------------------------------
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        if(mAuth.getCurrentUser() != null)
            mAuth.signOut();
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    FragmentManager fragmentManager = getSupportFragmentManager();

    if (id == R.id.nav_camera) {
        fragmentManager.beginTransaction().replace(R.id.content_menu, new InicioFragment()).commit();
        getSupportActionBar().setTitle("Inicio");
    } else if (id == R.id.nav_gallery) {
        fragmentManager.beginTransaction().replace(R.id.content_menu, new PerfilFragment()).commit();
        getSupportActionBar().setTitle("Perfil");

    } else if (id == R.id.nav_slideshow) {
        fragmentManager.beginTransaction().replace(R.id.content_menu, new AcercadeFragment()).commit();
        getSupportActionBar().setTitle("Acerca de");
    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

I get the following error

E/AndroidRuntime: FATAL EXCEPTION: main                               Process: com.juegosludicos.juegosludicosmejoradodos, PID: 26993
                                                                                        java.lang.IllegalArgumentException: Target must not be null.
                                                                                            at com.squareup.picasso.RequestCreator.into(RequestCreator.java:618)
                                                                                            at com.squareup.picasso.RequestCreator.into(RequestCreator.java:601)
                                                                                            at com.juegosludicos.juegosludicosmejoradodos.MenuActivity$1$1.onDataChange(MenuActivity.java:89)
                                                                                            at com.google.android.gms.internal.zzafp.zza(Unknown Source)
                                                                                            at com.google.android.gms.internal.zzagp.zzSu(Unknown Source)
                                                                                            at com.google.android.gms.internal.zzags$1.run(Unknown Source)
                                                                                            at android.os.Handler.handleCallback(Handler.java:739)
                                                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                            at android.os.Looper.loop(Looper.java:145)
                                                                                            at android.app.ActivityThread.main(ActivityThread.java:6934)
                                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                                            at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
                                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)

Apparently I'm calling badly in the part of

public void onDataChange(DataSnapshot dataSnapshot) {
                        String imageUrl=String.valueOf(dataSnapshot.child("Foto_Perfil").getValue());
                        if (URLUtil.isValidUrl(imageUrl)){
                            //Glide.with(Main3Activity.this).load(Uri.parse(imageUrl)).into(imgperfil);
-----------A esta linea marca el error----------------
                            Picasso.with(MenuActivity.this).load(Uri.parse(imageUrl)).into(imgperfil);
--------------------------------------------
                        }
                    }

within my mAuthListener=new FirebaseAuth.AuthStateListener() {...}

    
asked by kevvelas 28.11.2017 в 06:42
source

2 answers

1

At first glance you can see that you are not finding the ID imgperfil in the layout of your activity, which is logical since surely that image is defined in a different xml.

In order to access that imageview you will have to access the inflated layout of the navigation drawer and call findViewById on ESE layout.

    
answered by 06.12.2017 в 16:22
0

Seeing that you tried to use Glide and that now you have commented on it, you have taken a step back in your attempt, maybe because you did not implement that tool well, which is currently recommended to do what you want.

See what the documentation says:

Download images with FirebaseUI

  

FirebaseUI provides simple, customizable native links   and ready for production with the aim of eliminating the code   standard and promote Google best practices . With   FirebaseUI, you can download, cache and display images   quickly and easily from Cloud Storage, thanks to our   integration with Glide .

     

Firebase documentation: How to download files on Android .

Let's start again:

  • If you have not already done so, add FirebaseUI to your app/build.gradle :

    dependencies {
        // FirebaseUI Storage only
        compile 'com.firebaseui:firebase-ui-storage:0.6.0'
    }
    
  • Then, you can upload images directly from Storage to a ImageView : Here:

    • you will have to replace imageView with imgperfil that is, I suppose that of the profile.
    • in the context you can leave this , if it does not work, try putting MenuActivity.this instead.
    • the storageReference must be obtained as explained by firebase in the documentation, in the section Create a reference . I say this because, in the commented code, you were trying to get the image by parsing a URL. In Firebase, when you create a reference, you are inside, you do not have to parse anything, just use the resource. What you should take care of is to create the reference appropriately.

      // Lo ESENCIAL es que hagas referencia correctamente a tu imagen
      StorageReference storageReference = ...;
      
      // Este sería el imageView de tu Activity
      ImageView imageView = ...;
      
      // Ahora sólo llamas tu imagen con Glide
      Glide.with(this /* context */)
              .using(new FirebaseImageLoader())
              .load(storageReference)
              .into(imageView);
      
  • answered by 28.11.2017 в 11:21