Как загрузить изображение в приложение для Android с помощью Picasso и Android studio - PullRequest
0 голосов
/ 19 сентября 2019

Я пытаюсь загрузить изображение из URL в мое приложение для Android

ImageView img = (ImageView)view.findViewById(R.id.itemPicture);
String url = "https://storage.cloud.google.com/artifactory-images/old_fashioned_ring.PNG"
Picasso.get().load(url).resize(50, 50).centerCrop().into(img);

Ниже приведен код 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:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/iconProfilePicture"
                android:layout_width="wrap_content"
                android:layout_height="46dp"
                android:layout_marginTop="5dp"
                android:layout_marginBottom="5dp"
                android:contentDescription="@string/icon_of_user"
                app:layout_constraintBottom_toTopOf="@id/itemPicture"
                app:layout_constraintEnd_toStartOf="@+id/username"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:srcCompat="@mipmap/ic_launcher_round" />

            <ImageView
                android:id="@+id/itemPicture"
                android:layout_width="0dp"
                android:layout_height="500dp"
                android:contentDescription="@string/image_of_artifact"
                android:cropToPadding="false"
                android:scaleType="centerCrop"
                app:layout_constraintBottom_toTopOf="@id/textViewTitle"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/iconProfilePicture"
                app:srcCompat="@mipmap/ic_launcher_round" />

            <TextView
                android:id="@+id/username"
                android:layout_width="0dp"
                android:layout_height="19dp"
                android:layout_marginEnd="50dp"
                android:layout_marginRight="50dp"
                android:text="@string/sample_username"
                app:layout_constraintBottom_toTopOf="@+id/itemPicture"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toEndOf="@+id/iconProfilePicture"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:id="@+id/textViewTitle"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:paddingLeft="15dp"
                android:paddingTop="0dp"
                android:paddingRight="15dp"
                android:paddingBottom="0dp"
                android:text="@string/sample_text"
                android:textStyle="bold"
                app:layout_constraintBottom_toTopOf="@+id/textViewDescription"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/itemPicture" />

            <TextView
                android:id="@+id/textViewDescription"
                android:layout_width="0dp"
                android:layout_height="146dp"
                android:paddingLeft="15dp"
                android:paddingTop="8dp"
                android:paddingRight="15dp"
                android:paddingBottom="8dp"
                android:text="@string/sample_description"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@id/textViewTitle" />
        </androidx.constraintlayout.widget.ConstraintLayout>
    </ScrollView>

</androidx.constraintlayout.widget.ConstraintLayout>

Как работают код XML и Javaсвязать?В данный момент я использую R.id.itemPicture

Но я не знаю, правильный ли это идентификатор.

Когда я запускаю приложение, оно просто сразу падает в эмуляторе

Вот вывод консоли:

  D/AndroidRuntime: Shutting down VM
  E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.themanbuns, PID: 7508
java.lang.IllegalArgumentException: Target must not be null.
    at com.squareup.picasso.RequestCreator.into(RequestCreator.java:682)
    at com.squareup.picasso.RequestCreator.into(RequestCreator.java:665)
    at com.example.themanbuns.fragments.ItemsFragment$1.onComplete(ItemsFragment.java:189)
    at com.google.android.gms.tasks.zzj.run(Unknown Source:4)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6494)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 

Вот полный фрагмент:

    package com.example.themanbuns.fragments;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.example.themanbuns.activities.MainActivity;
import com.example.themanbuns.data.Item;
import com.example.themanbuns.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.tabs.TabLayout;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.Map;

public class ItemsFragment extends Fragment {
    public static final int CARD_VIEW = 0;
    public static final int LIST_VIEW = 1;

    public static final int NUM_TABS = 2;
    public static final int MY_ITEMS_POS = 0;
    public static final int ITEMS_SHARED_WITH_ME_POS = 1;

    private ItemsTabFragment myItemsFragment;
    private ItemsTabFragment sharedItemsFragment;

    private ItemsPagerAdapter itemsPagerAdapter;
    private ViewPager viewPager;
    private TabLayout tabLayout;

    private ArrayList<Item> myItems; // items stored in ArrayList
    private ArrayList<Item> itemsSharedWithMe;
    private ArrayList<ImageView> myImages;

    private View view;

    private Menu itemsMenu;
    private int itemDisplayType;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view =  inflater.inflate(R.layout.fragment_items, container, false);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setHasOptionsMenu(true);
        createItems(); // this is the example created
        setupItemTabs(); // this handles the two tabs at top: my items and items shared with me
        itemDisplayType = ((MainActivity) getActivity()).getItemDisplayType(); // this sets list or card view (when you go to options view type)
    }

    // this handles the two tabs at top: my items and items shared with me
    private void setupItemTabs() {
        itemsPagerAdapter = new ItemsPagerAdapter(getChildFragmentManager());
        viewPager = view.findViewById(R.id.viewPager);
        viewPager.setAdapter(itemsPagerAdapter);

        tabLayout = view.findViewById(R.id.tabLayout);
        tabLayout.setupWithViewPager(viewPager);
    }

    public class ItemsPagerAdapter extends FragmentPagerAdapter {

        public ItemsPagerAdapter(FragmentManager fragmentManager) {
            super (fragmentManager, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        }

        // this generates my items and shared items
        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case MY_ITEMS_POS:
                    myItemsFragment = new ItemsTabFragment(myItems, View.VISIBLE, itemDisplayType);
                    return myItemsFragment;
                case ITEMS_SHARED_WITH_ME_POS:
                    sharedItemsFragment = new ItemsTabFragment(itemsSharedWithMe, View.GONE, itemDisplayType);
                    return sharedItemsFragment;
                default:
                    throw new RuntimeException();
            }
        }

        @Override
        public int getCount() {
            return NUM_TABS;
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case MY_ITEMS_POS:
                    return getString(R.string.my_items);
                case ITEMS_SHARED_WITH_ME_POS:
                    return getString(R.string.items_shared_with_me);
                default:
                    throw new RuntimeException();
            }
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.options_menu_items_fragment, menu);
        itemsMenu = menu;

        switch (itemDisplayType) {
            case CARD_VIEW:
                itemsMenu.findItem(R.id.cardView).setChecked(true);
                itemsMenu.findItem(R.id.listView).setChecked(false);
                changeLayoutType(itemDisplayType);
                break;
            case LIST_VIEW:
                itemsMenu.findItem(R.id.cardView).setChecked(false);
                itemsMenu.findItem(R.id.listView).setChecked(true);
                changeLayoutType(itemDisplayType);
                break;
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.cardView:
                item.setChecked(true);
                itemsMenu.findItem(R.id.listView).setChecked(false);
                changeLayoutType(CARD_VIEW);
                return true;
            case R.id.listView:
                item.setChecked(true);
                itemsMenu.findItem(R.id.cardView).setChecked(false);
                changeLayoutType(LIST_VIEW);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    // this sets list or card view (when you go to options view type)
    public void changeLayoutType(int displayType) {
        itemDisplayType = displayType;
        ((MainActivity) getActivity()).setItemDisplayType(displayType);
        if ((myItemsFragment != null) && (sharedItemsFragment != null)) {
            myItemsFragment.setLayoutType(displayType);
            sharedItemsFragment.setLayoutType(displayType);
        }
    }

    // example items displayed
    public void createItems() {
        myItems = new ArrayList<Item>();
        itemsSharedWithMe = new ArrayList<Item>();

        ((MainActivity) getActivity()).getFirebaseFirestore().collection("items")
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            for (QueryDocumentSnapshot document : task.getResult()) {
                                if (document.getId().equals("lachie")) {
                                    addToMyItems(document.getData());
                                    String imageUrl = document.getData().get("image").toString();

                                    ImageView img = (ImageView)view.findViewById(R.id.itemPicture);
                                    String url = "https://storage.cloud.google.com/artifactory-images/old_fashioned_ring.PNG";
                                    Picasso.get().load(url).resize(50, 50).centerCrop().into(img);

                                }
                            }
                        } else {
                            System.out.println("failure");
                        }
                    }
                });
    }

    public void addToMyItems(Map<String, Object> item) {
        String name = item.get("name").toString();
        String description = item.get("description").toString();
        String image = item.get("image").toString();

        myItems.add(new Item(name, description, image));

        myItemsFragment.notifyDataSetChanged();
    }

    public void addToSharedItems(Item item) {
        itemsSharedWithMe.add(item);
    }

Таким образом, он говорит: «target не должен быть нулевым».Из того, что я понимаю, цель - объект ImageView Заранее спасибо

Ответы [ 2 ]

0 голосов
/ 19 сентября 2019

Используйте getView() или параметр view от реализации метода onViewCreated.Возвращает корневое представление для фрагмента (, возвращенное методом onCreateView () ).При этом вы можете позвонить findViewById().

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    ImageView imageView = (ImageView) view.findViewById(R.id.itemPicture);
    // or  (ImageView) getView().findViewById(R.id.itemPicture);
    String url = "https://storage.cloud.google.com/artifactory-images/old_fashioned_ring.PNG"
    Picasso.get().load(url).resize(50, 50).centerCrop().into(imageView);
    .....

ОБНОВЛЕНИЕ

Вы можете изменить onCreateView(), setupItemTabs() и createItems в ItemsFragment вроде следующего:

        ................
        private ImageView img;

        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            view =  inflater.inflate(R.layout.fragment_items, container, false);
            img = (ImageView)view.findViewById(R.id.itemPicture);
            viewPager = view.findViewById(R.id.viewPager);
            tabLayout = view.findViewById(R.id.tabLayout);
            return view;
        }
        // this handles the two tabs at top: my items and items shared with me
        private void setupItemTabs() {
            itemsPagerAdapter = new ItemsPagerAdapter(getChildFragmentManager());
            viewPager.setAdapter(itemsPagerAdapter);
            tabLayout.setupWithViewPager(viewPager);
        }
        // example items displayed
        public void createItems() {
            myItems = new ArrayList<Item>();
            itemsSharedWithMe = new ArrayList<Item>();

            ((MainActivity) getActivity()).getFirebaseFirestore().collection("items")
                    .get()
                    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                        @Override
                        public void onComplete(@NonNull Task<QuerySnapshot> task) {
                            if (task.isSuccessful()) {
                                for (QueryDocumentSnapshot document : task.getResult()) {
                                    if (document.getId().equals("lachie")) {
                                        addToMyItems(document.getData());
                                        String imageUrl = document.getData().get("image").toString();


                                        String url = "https://storage.cloud.google.com/artifactory-images/old_fashioned_ring.PNG";
                                        Picasso.get().load(url).resize(50, 50).centerCrop().into(img);

                                    }
                                }
                            } else {
                                System.out.println("failure");
                            }
                        }
                    });
        }

Вам это поможет.

0 голосов
/ 19 сентября 2019

Ваш URL выглядит как автоматическое перенаправление на другой сервер.Вы можете попробовать решение здесь Получить перенаправленный URL от Пикассо ?

...