Мое приложение не может показать изображение на моем домашнем фрагменте, даже после того, как мой тост говорит, что успешно добавлено, ни одно решение онлайн не помогло - PullRequest
0 голосов
/ 08 апреля 2020

Вот код исходного фрагмента, он работает нормально и без ошибок, единственная проблема в том, что он не публикует sh и изображение на домашней странице фрагмента на моем эмуляторе android. проверил онлайн на полезные советы, но ни один не помог. Сильно ожидая. Спасибо

public class HomeFragment1 extends Fragment {

 RecyclerView postRecyclerView;
    PostAdapter postAdapter;
    FirebaseDatabase firebaseDatabase;
    DatabaseReference databaseReference;
    List<Post> postList;



    public HomeFragment1() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HomeFragment1.
     */
    // TODO: Rename and change types and number of parameters
    public static HomeFragment1 newInstance(String param1, String param2) {
        HomeFragment1 fragment = new HomeFragment1();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View fragmentView = inflater.inflate(R.layout.fragment_home1, container, false);
        postRecyclerView = fragmentView.findViewById(R.id.postCT);
        postRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        postRecyclerView.setHasFixedSize(true);
        firebaseDatabase = FirebaseDatabase.getInstance();
        databaseReference = firebaseDatabase.getReference("Posts");
        return fragmentView;

    }

    @Override
    public void onStart() {
        super.onStart();

        //Get List Post
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                postList = new ArrayList<>();
                for(DataSnapshot postSnap: dataSnapshot.getChildren()){
                    Post post = postSnap.getValue(Post.class);
                    postList.add(post);
                }

                postAdapter = new PostAdapter(getActivity(),postList);
                postRecyclerView.setAdapter(postAdapter);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }
}

Вот XML для фрагмента дома, который будет отображаться. К ней прикреплена строка XML, содержащая образец изображения для публикации.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Activities.ui.home.HomeFragment1">


    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/postCT"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

Вот строка, в которой код активности Home удалил ненужный код, который не связан с загрузкой изображения.

public class Home_PersonalActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{



    private AppBarConfiguration mAppBarConfiguration;
    ActionBarDrawerToggle actionBarDrawerToggle;
    FirebaseUser currentUser;
    FirebaseAuth mAuth;
    Dialog popAddPost;
    ImageView popUpUserImage, popUpPostImage, popupAddBtn;
    TextView popUpTittle, popUpDescription;
    ProgressBar popUpProgressBar;
    private static final int PreqCode = 2;
    private static int REQUESCODE = 2;
    private Uri pickedPicUri = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home__personal);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        DrawerLayout drawer = findViewById(R.id.drawer_layout);


        mAuth = FirebaseAuth.getInstance();
        currentUser =  mAuth.getCurrentUser();




        // Initialize pop_up from the popup drawable xml
        initialisePopUp();

        setUpPopupImageClick();



            FloatingActionButton fab = findViewById(R.id.fab);
            fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popAddPost.show();

         }
      });

        actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(actionBarDrawerToggle);
        actionBarDrawerToggle.setDrawerIndicatorEnabled(true); // This code here is for the hamburger sign that opens up the drawer
        actionBarDrawerToggle.syncState();// this is for the opening and closing and normalization of the hamburger sign

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

        updateNavHeader();

        // Set the home fragment as default entry point when user logs in
        getSupportFragmentManager().beginTransaction().replace(R.id.container, new HomeFragment1()).commit();
        getSupportActionBar().setTitle("Home");
      //  getSupportFragmentManager().beginTransaction().replace(R.id.container, new HomeFragment1()).commit();

//        // Passing each menu ID as a set of Ids because each
//        // menu should be considered as top level destinations.
//        mAppBarConfiguration = new AppBarConfiguration.Builder(
//                R.id.nav_home, R.id.nav_profile, R.id.nav_settings, R.id.nav_logout)
//                .setDrawerLayout(drawer)
//                .build();
//        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
//        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
//        NavigationUI.setupWithNavController(navigationView, navController);

  } 
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.home__personal, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {

        int id = item.getItemId();

        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);

    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.nav_home) {

            getSupportActionBar().setTitle("Home");
            getSupportFragmentManager().beginTransaction().replace(R.id.container, new HomeFragment1()).commit();



        } else if (id == R.id.nav_profile) {
            getSupportActionBar().setTitle("Profile");
            getSupportFragmentManager().beginTransaction().replace(R.id.container, new ProfileFragment1()).commit();

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

            getSupportActionBar().setTitle("Settings");
            getSupportFragmentManager().beginTransaction().replace(R.id.container, new SettingFragment1()).commit();
        } else if (id == R.id.nav_logout) {

            FirebaseAuth.getInstance().signOut();
            Intent LoginActivity = new Intent(getApplicationContext(), loginActivity.class);
            startActivity(LoginActivity);
            finish();

        }

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

        return true;
    }

    public void updateNavHeader(){

        NavigationView navigationView = findViewById(R.id.nav_view);
        View headerView = navigationView.getHeaderView(0);
        TextView navUsername = headerView.findViewById(R.id.nav_UserName);
        TextView navUserMail = headerView.findViewById(R.id.nav_UserMail);
        ImageView navUerPic = headerView.findViewById(R.id.nav_UserPhoto);


        navUserMail.setText(currentUser.getEmail());
        navUsername.setText(currentUser.getDisplayName());


        // Using glide to load user image
        Glide.with(this).load(currentUser.getPhotoUrl()).into(navUerPic);

    }
}

Вот 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="250dp">

    <ImageView
        android:id="@+id/row_post_imageID"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:scaleType="centerCrop"
        android:contentDescription="@string/image"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        android:src="@drawable/ic_launcher_background" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="0dp"
        android:layout_height="85dp"
        android:contentDescription="@string/small"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="@+id/row_post_imageID"
        app:layout_constraintTop_toTopOf="@+id/row_post_imageID"
        app:layout_constraintVertical_bias="1.0"
        android:src="@drawable/black_gradient" />

    <TextView
        android:id="@+id/row_post_tittle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginBottom="16dp"
        android:text="@string/textview"
        android:textColor="#ffffff"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/row_post_userProfImg"
        app:layout_constraintStart_toStartOf="@+id/imageView2"
        app:layout_constraintTop_toTopOf="@+id/imageView2" />

    <ImageView
        android:id="@+id/row_post_userProfImg"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:contentDescription="@string/tiny"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="@+id/imageView2"
        app:layout_constraintVertical_bias="0.567"
        tools:srcCompat="@tools:sample/avatars" />
</androidx.constraintlayout.widget.ConstraintLayout>

1 Ответ

0 голосов
/ 09 апреля 2020

Ребята Я наконец-то решил эту проблему, переставив файлы моего поста 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="250dp">

    <ImageView
        android:id="@+id/row_post_imageID"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:scaleType="centerCrop"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:src="@drawable/ic_launcher_background" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="0dp"
        android:layout_height="85dp"
        app:layout_constraintBottom_toBottomOf="@+id/row_post_imageID"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        android:src="@drawable/black_gradient" />

    <TextView
        android:id="@+id/row_post_tittle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:text="TextView"
        android:textColor="#fff"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/row_post_userProfImg"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/imageView2" />

    <ImageView
        android:id="@+id/row_post_userProfImg"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/imageView2"
        app:layout_constraintTop_toTopOf="@+id/imageView2"
        tools:srcCompat="@tools:sample/avatars" />
...