Список массивов (CardView) с тем же макетом, но разными данными - PullRequest
0 голосов
/ 11 апреля 2020

Отредактированное сообщение: 21 апреля 2020 года

Итак, я получаю исключение NullPointerException, когда я сейчас пытаюсь вызвать мое описание для моей новой активности клиентов. Кажется, я не могу вызвать свое описание из моего ArrayList в новый Activity TextView. Я мог что-то упустить.

MuaActivity (MainActivity),

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.inputmethod.EditorInfo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

import Adapters.MuaAdapter;
import CustomerActivities.Customer1Activity;

public class MuaActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;
    private MuaAdapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mua_list);

        getSupportActionBar().setTitle("Make Up Artists");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        final ArrayList<MuaView> muaView = new ArrayList<>();
        muaView.add(new MuaView(R.drawable.mua_image, "Shima Matin Bridal Services", "Shima Matin started in 2012"));

        // ArrayList

        mRecyclerView = findViewById(R.id.recycler_view_list);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(this);
        mAdapter = new MuaAdapter(muaView);

        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);

        // Item Click listener for CardView and Parcel CardView to new Intent

        mAdapter.setOnItemClickListener(new MuaAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent(MuaActivity.this, Customer1Activity.class);
                intent.putExtra("Customer's Details", muaView.get(position));
                startActivity(intent);
            }

        });

    }

    // Filter/Search Bar

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.search, menu);

        MenuItem searchItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) searchItem.getActionView();

        searchView.setImeOptions(EditorInfo.IME_ACTION_DONE);

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                mAdapter.getFilter().filter(newText);
                return false;
            }
        });
        return true;
    }
}

MuaAdapter,

import android.com.example.weddingappfinale.MuaView;
import android.com.example.weddingappfinale.R;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class MuaAdapter extends RecyclerView.Adapter<MuaAdapter.MuaViewHolder> implements Filterable {

    private ArrayList<MuaView> mMuaView;
    private ArrayList<MuaView> mMuaViewFull;
    private OnItemClickListener mListener;

    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        mListener = listener;
    }

    public static class MuaViewHolder extends RecyclerView.ViewHolder {
        public ImageButton mImageButton;
        public TextView mTextView1;
        public TextView mDescription;

        public MuaViewHolder(@NonNull View itemView, final OnItemClickListener listener) {
            super(itemView);
            mImageButton = itemView.findViewById(R.id.mua_imageButton);
            mTextView1 = itemView.findViewById(R.id.mua_title);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listener != null) {
                        int position = getAdapterPosition();
                        if (position != RecyclerView.NO_POSITION) {
                            listener.onItemClick(position);
                        }
                    }
                }
            });

            mImageButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listener != null) {
                        int position = getAdapterPosition();
                        if (position != RecyclerView.NO_POSITION) {
                            listener.onItemClick(position);
                        }
                    }
                }
            });
        }
    }

    public MuaAdapter(ArrayList<MuaView> muaView) {
       mMuaView = muaView;
       mMuaViewFull = new ArrayList<>(muaView);
    }

    @Override
    public MuaViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.mua_view, parent, false);
        MuaViewHolder mvh = new MuaViewHolder(v, mListener);
        return mvh;
    }

    @Override
    public void onBindViewHolder(@NonNull MuaViewHolder holder, int position) {
        MuaView currentView = mMuaView.get(position);

        holder.mImageButton.setImageResource(currentView.getImageResource());
        holder.mTextView1.setText(currentView.getText1());
    }

    @Override
    public int getItemCount() {
        return mMuaView.size();
    }

    public Filter getFilter() {
        return MuaFilter;
    }

    private Filter MuaFilter = new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            List<MuaView> filteredList = new ArrayList<>();

            if (constraint == null || constraint.length() == 0) {
                filteredList.addAll(mMuaViewFull);
            } else {
                String filterPattern = constraint.toString().toLowerCase().trim();

                for (MuaView item : mMuaViewFull) {
                    if (item.getText1().toLowerCase().contains(filterPattern)) {
                        filteredList.add(item);
                    }
                }
            }

            FilterResults results = new FilterResults();
            results.values = filteredList;

            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            mMuaView.clear();
            mMuaView.addAll((ArrayList) results.values);
            notifyDataSetChanged();

        }
    };
}

ModelClass MuaView,

    package android.com.example.weddingappfinale;

import android.os.Parcel;
import android.os.Parcelable;

public class MuaView implements Parcelable {
    private int mImageResource;
    private String mText1;
    private String mDescription;
    private String mServices1;
    private String mServices2;
    private String mContact;
    private String mAddress;

    public MuaView(int imageResource, String text1, String description) {
        mImageResource = imageResource;
        mText1 = text1;
        mDescription = description;

    }

    protected MuaView(Parcel in) {
        mImageResource = in.readInt();
        mText1 = in.readString();
    }

    public static final Creator<MuaView> CREATOR = new Creator<MuaView>() {
        @Override
        public MuaView createFromParcel(Parcel in) {
            return new MuaView(in);
        }

        @Override
        public MuaView[] newArray(int size) {
            return new MuaView[size];
        }
    };

    public MuaView(int mua_image, String shima_matin_bridal_services, int catering_title) {
    }

    public int getImageResource() {
        return mImageResource;
    }

    public String getText1() {
        return mText1;
    }

    public void setmDescription(String mDescription) {
        this.mDescription = mDescription;
    }

    public String getmDescription() {
        return mDescription;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(mImageResource);
        dest.writeString(mText1);
    }
}

activity_customer. xml

    <?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView 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">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent">

        <ImageButton
            android:id="@+id/image_customer"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:layout_margin="4dp"
            android:adjustViewBounds="true"
            android:background="@drawable/ic_launcher_background"
            android:scaleType="centerCrop" />

        <TextView
            android:id="@+id/title_customer"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/image_customer"
            android:layout_centerHorizontal="true"
            android:layout_margin="4dp"
            android:fontFamily="@font/open_sans_semibold"
            android:text="" />

        <TextView
            android:id="@+id/description"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Description:"
            android:layout_below="@id/title_customer"
            android:layout_centerHorizontal="true"
            android:fontFamily="@font/open_sans_extrabold"/>

        <TextView
            android:id="@+id/descriptionVendor"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Description of Vendors"
            android:layout_below="@id/description"
            android:layout_centerHorizontal="true"/>

        <TextView
            android:id="@+id/services"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/descriptionVendor"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="8dp"
            android:fontFamily="@font/open_sans_extrabold"
            android:text="@string/services" />

        <TextView
            android:id="@+id/services1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/services"
            android:layout_centerHorizontal="true"
            android:layout_toEndOf="@id/services"
            android:layout_toRightOf="@id/services"
            android:text="Services1" />

        <TextView
            android:id="@+id/services2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/services1"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="4dp"
            android:layout_toRightOf="@id/services"
            android:text="Services2" />

        <TextView
            android:id="@+id/gallery"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/services2"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="8dp"
            android:fontFamily="@font/open_sans_extrabold"
            android:text="@string/gallery" />

        <com.denzcoskun.imageslider.ImageSlider
            android:id="@+id/imageslider"
            android:layout_width="wrap_content"
            android:layout_height="200dp"
            android:layout_below="@id/gallery"
            android:layout_centerHorizontal="true"
            android:layout_margin="4dp"
            app:delay="0"
            app:placeholder="@drawable/mua_image" />

        <TextView
            android:id="@+id/contact"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/imageslider"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="8dp"
            android:fontFamily="@font/open_sans_extrabold"
            android:text="Contact:"/>

        <TextView
            android:id="@+id/contactVendor"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/contact"
            android:layout_centerHorizontal="true"
            android:text="ContactVendor" />

        <TextView
            android:id="@+id/address"
            android:layout_below="@id/contactVendor"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Address:"
            android:layout_centerHorizontal="true"
            android:fontFamily="@font/open_sans_extrabold"/>

        <TextView
            android:id="@+id/addressvendor"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/address"
            android:text="AddressVendor"
            android:layout_centerHorizontal="true"/>


    </RelativeLayout>
</androidx.core.widget.NestedScrollView>

CustomerActivity,

 package CustomerActivities;

import android.com.example.weddingappfinale.MuaView;
import android.com.example.weddingappfinale.R;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.denzcoskun.imageslider.ImageSlider;
import com.denzcoskun.imageslider.models.SlideModel;

import java.util.ArrayList;
import java.util.List;

public class Customer1Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer1_mua);
        Intent intent = getIntent();
        MuaView muaView = intent.getParcelableExtra("Customer's Details");

        int imageRes = muaView.getImageResource();
        String line1 = muaView.getText1();
        String description = muaView.getmDescription();

        ImageButton imageButton = findViewById(R.id.image_customer);
        imageButton.setImageResource(imageRes);

        TextView textView = findViewById(R.id.descriptionVendor);
        textView.setText(description);

        TextView textView1 = findViewById(R.id.title_customer);
        textView1.setText(line1);

        ImageSlider imageSlider = findViewById(R.id.imageslider);
        List<SlideModel> slideModels = new ArrayList<>();
        slideModels.add(new SlideModel(R.drawable.catering_image));
        slideModels.add(new SlideModel(R.drawable.entertainment_image));
        imageSlider.setImageList(slideModels, true);


    }
}

Ответы [ 3 ]

1 голос
/ 11 апреля 2020

Вам не нужна база данных для передачи данных в класс модели и загрузки в rcyclerview через класс адаптера. Для этого у вас должен быть макет просмотра или карты. Я рекомендую переработчик просмотра, так как просмотр карт - старый подход ... тогда Вы должны хранить все свои данные в массиве. просто для примера я показываю вам список данных типа строки:

List yourListName = new ArrayList <>; Затем l oop ваши данные и передать их в Arraylist, как это.

yourListName.add (ваши данные здесь);

и передать их конструктору класса адаптера, в который вы добавили Arraylist параметр. для загрузки данных вам нужен класс модели, класс адаптера, и после этого действия вы передадите массив, в который хотите показать свои данные. и arraylist мы передаем в конструктор класса адаптера, как я сказал.

Я проверяю код, я добавлю другой ответ.

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

Если ответ не помогает, я хотел бы добавить простой код, который может дать вам некоторые подсказки.

Xml Основной файл, в котором находится мой recyclerView:

<?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=".MainActivity">


    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycleView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:listitem="@layout/sample_recyclerview"/>

</RelativeLayout>

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="165dp"
    android:orientation="vertical">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="5dp"
        app:cardCornerRadius="5dp"
        app:cardElevation="5dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/imageView"
                android:layout_width="match_parent"
                android:layout_height="120dp"
                tools:srcCompat="@drawable/download"
                android:scaleType="centerCrop"/>

            <TextView
                android:id="@+id/textView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:background="@color/pinkish"
                android:gravity="center"
                android:shadowColor="#FFFFFF"
                android:text="TextView"
                android:textColor="#FFFFFF"
                android:textSize="18sp"
                android:textStyle="bold" />
        </LinearLayout>

    </androidx.cardview.widget.CardView>

</RelativeLayout>

Вот мой класс модели для загрузки данных:

public class RecipeModel {

  private   int pic;
  private   String text;

    public RecipeModel(int pic, String text) {
        this.pic = pic;
        this.text = text;
    }

    public int getPic() {
        return pic;
    }

    public void setPic(int pic) {
        this.pic = pic;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}

А вот класс адаптера показывает, как загрузить данные из класса модели и загрузить в созданный макет внутри метода адаптера Oncreate:

public class RecipeAdapter extends RecyclerView.Adapter<RecipeAdapter.viewHolder> {

    ArrayList<RecipeModel>  List;
    Context context;

    public RecipeAdapter(ArrayList<RecipeModel> list, Context context) {
        List = list;
        this.context = context;
    }

    @NonNull
    @Override
    public viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.sample_recyclerview, parent, false);
        return new viewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull viewHolder holder, int position) {
        RecipeModel model = List.get(position);

        holder.imageView.setImageResource(model.getPic());
        holder.textView.setText(model.getText());

        holder.imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(context, "Item is clicked", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public int getItemCount() {
        return List.size();
    }

    public class viewHolder extends RecyclerView.ViewHolder {

        ImageView imageView;
        TextView textView;
        public viewHolder(@NonNull View itemView) {
            super(itemView);

            imageView = itemView.findViewById(R.id.imageView);
            textView = itemView.findViewById(R.id.textView);
        }
    }
}

и здесь вы передаете значения из действия, в котором вы создали тэг recyclerview: , и я прокомментировал другой стиль recyclerView, который можно использовать, чтобы увидеть разницу.

public class MainActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = (RecyclerView) findViewById(R.id.recycleView);

        ArrayList<RecipeModel> list = new ArrayList<>();

        list.add(new RecipeModel(R.drawable.cc, "A Picture"));
        list.add(new RecipeModel(R.drawable.ccccc, "A Picture"));
        list.add(new RecipeModel(R.drawable.ddd, "A Picture"));
        list.add(new RecipeModel(R.drawable.download, "A Picture"));
        list.add(new RecipeModel(R.drawable.flower2, "A Picture"));
        list.add(new RecipeModel(R.drawable.images, "A Picture"));
        list.add(new RecipeModel(R.drawable.littlegirl, "A Picture"));
        list.add(new RecipeModel(R.drawable.pler4, "A Picture"));
        list.add(new RecipeModel(R.drawable.plw, "A Picture"));
        list.add(new RecipeModel(R.drawable.qwe, "A Picture"));
        list.add(new RecipeModel(R.drawable.port, "A Picture"));
        list.add(new RecipeModel(R.drawable.rg5fs, "A Picture"));

        RecipeAdapter adapter = new RecipeAdapter(list, this);
        recyclerView.setAdapter(adapter);

//        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
//        recyclerView.setLayoutManager(linearLayoutManager);

//        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, true);
//        recyclerView.setLayoutManager(linearLayoutManager);

//        GridLayoutManager layoutManager = new GridLayoutManager(this, 3);
//        recyclerView.setLayoutManager(layoutManager);
        StaggeredGridLayoutManager staggered = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(staggered);
    }
}
0 голосов
/ 12 апреля 2020

Данные, которые вы передаете из Customer1Activity , нуждаются в классе модели Как:

public class SlideModel{

int Imagepath;

public SlideModel(int Imagepath)
{
   this.Imagepath = Imagepath;

}

 public int getImagepath() {
        return Imagepath;
    }

    public void setImagepath(int Imagepath) {
        this.Imagepath = Imagepath;
    }

}

и где в MuaActivity вам нужен класс модели как:

public class MuaView{

  private   int pic;
  private   String text;

    public RecipeModel(int pic, String text) {
        this.pic = pic;
        this.text = text;
    }

    public int getPic() {
        return pic;
    }

    public void setPic(int pic) {
        this.pic = pic;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}

и внесли следующие изменения в свой адаптер:

public void onBindViewHolder(@NonNull MuaViewHolder holder, int position) {
    MuaView currentView = mMuaView.get(position);

    holder.mImageButton.setImageResource(currentView.getPic());
    holder.mTextView1.setText(currentView.getText());
}

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

...