简体   繁体   中英

Passing MainActivity's data via adapter

I'm new to android and java but in my very first app I'm kinda doing play store, the first thing you see on play store and then go to the second activity and see that whole list there. I've built the horizontal ArrayList and i succeeded to build GridView of second activity as well, my ArrayList is static i mean it's not using any server.

My problem is how can i send MainActivity 's data via the adapter which is situated on it to MainActivity2 .

Here is my Main Activity which my data is situated there:

public class MainActivity extends AppCompatActivity {

private ArrayList<SectionDataModel> allSampleData;


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

    allSampleData = new ArrayList<>();


    RecyclerView recyclerView = findViewById(R.id.my_recycler_view1);
    recyclerView.setHasFixedSize(true);
    RecyclerViewDataAdapter adapter = new RecyclerViewDataAdapter(allSampleData, this);
    recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
    recyclerView.setAdapter(adapter);


    EssentialData();



}

public void EssentialData() {
    SectionDataModel Unit1 = new SectionDataModel();
    Unit1.setHeaderTitle("Unit 1");


    ArrayList<SingleItemModel> singleItemModels = new ArrayList<>();

    singleItemModels.add(new SingleItemModel("Word ", "Pronunciation", "Example", R.drawable.alferet));
    singleItemModels.add(new SingleItemModel("The Apple", "Apple Store Is Open", "Description book", R.drawable.alferet));
    singleItemModels.add(new SingleItemModel("The Apple", "Apple Store Is Open", "Description book", R.drawable.soft));
    singleItemModels.add(new SingleItemModel("The Apple", "Apple Store Is Open", "Description book", R.drawable.alferet));
    singleItemModels.add(new SingleItemModel("The Apple", "Apple Store Is Open", "Description book", R.drawable.alferet));
    singleItemModels.add(new SingleItemModel("The Apple", "Apple Store Is Open", "Description book", R.drawable.alferet));
    singleItemModels.add(new SingleItemModel("The Apple", "Apple Store Is Open", "Description book", R.drawable.alferet));
    singleItemModels.add(new SingleItemModel("The Apple", "Apple Store Is Open", "Description book", R.drawable.alferet));
    singleItemModels.add(new SingleItemModel("The Apple", "Apple Store Is Open", "Description book", R.drawable.alferet));
    singleItemModels.add(new SingleItemModel("The Apple", "Apple Store Is Open", "Description book", R.drawable.alferet));
    singleItemModels.add(new SingleItemModel("The Apple", "Apple Store Is Open", "Description book", R.drawable.alferet));
    singleItemModels.add(new SingleItemModel("The Apple", "Apple Store Is Open", "Description book", R.drawable.alferet));
    singleItemModels.add(new SingleItemModel("The Apple", "Apple Store Is Open", "Description book", R.drawable.alferet));


    Unit1.setAllItemInSection(singleItemModels);
    allSampleData.add(Unit1);


}
  }

And my SectionDataAdapter which only from it i can send Data to Second MainActivity because if i do it from MainActivity itself it returned Null :

public class SectionDataAdapter extends RecyclerView.Adapter<SectionDataAdapter.SingleItemRowHolder>{

private final Context mContext;

private ArrayList<SingleItemModel> itemModels;


//the constructor
public SectionDataAdapter(ArrayList<SingleItemModel> itemModels, Context mContext) {
    this.itemModels = itemModels;
    this.mContext = mContext;
}


@NonNull
@Override
public SingleItemRowHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_single_card, null);
    SingleItemRowHolder singleItemRowHolder = new SingleItemRowHolder(view);
    return singleItemRowHolder;
}




@Override
public void onBindViewHolder(@NonNull SingleItemRowHolder holder, int position) {
    SingleItemModel itemModel = itemModels.get(position);
    holder.tvTitle.setText(itemModel.getWord());
    holder.mitemImage.setImageResource(itemModel.getImage());
}


@Override
public int getItemCount() {return (null != itemModels ? itemModels.size() : 0);}

public class SingleItemRowHolder extends RecyclerView.ViewHolder {
    protected TextView tvTitle;
    protected ImageView mitemImage;



    public SingleItemRowHolder(final View itemView) {

        super(itemView);
        //Intent to start next activity
        final Intent intent = new Intent(mContext, ActivityDialogTheme.class);
        final Intent intent1 = new Intent(mContext, MainActivity2.class);

        final Activity activity = (Activity) mContext;

        this.mitemImage = itemView.findViewById(R.id.itemImage);
        this.tvTitle = itemView.findViewById(R.id.tvTitle);


        itemView.setOnClickListener(new View.OnClickListener(){


            @Override
            public void onClick(View v){
                Toast.makeText(v.getContext(), tvTitle.getText(), LENGTH_SHORT).show();
                //passing data to Tab1Fragment

                mContext.startActivity(intent1);
            }
        });
        itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Toast.makeText(mContext,tvTitle.getText(), Toast.LENGTH_SHORT).show();
                mContext.startActivity(intent);

                //appearing animation
                activity.overridePendingTransition(R.anim.bottom_in, R.anim.fade_in_right);
                return true;
            }
        });
        }
    }
}

And how to receive it? Somebody help me.

Your SectionDataModel need to implement Parceble interface. Like below you can implement -

public class Person implements Parcelable{
String name;
int age;
String sex;

public Person(String name, int age, String sex) {
    this.name = name;
    this.age = age;
    this.sex = sex;
} 
 public static final Creator<Person> CREATOR = new Creator<Person>() {
    @Override
    public Person createFromParcel(Parcel in) {
        return new BeanClass(in);
    }

    @Override
    public Person[] newArray(int size) {
        return new Person[size];
    }
};
@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(name);
    dest.writeInt(age);
    dest.writeString(sex);
}
}

Passing data to fragment or activity from your adapter class -

@Override
    public void onClick(View v){
        Toast.makeText(v.getContext(), tvTitle.getText(), LENGTH_SHORT).show();
        //passing data to Tab1Fragment
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("SectionDataModels", sectionDataModelList);
        intent1.putExtras(bundle);
        mContext.startActivity(intent1);
    }

Receiving SectionDataModelList in the activity -

ArrayList<SectionDataModel> listFromActivity =new ArrayList<>();

listFromActivity=this.getIntent().getExtras().getParcelableArrayList("SectionDataModels");

    if (listFromActivity1 != null) {

        Log.d("listis",""+listFromActivity1.toString());
    }

Also, you can try to receive intent data with this way - If you need

Bundle bundle = getActivity().getIntent().getExtras();
model = bundle.getParcelable("SectionDataModels");

OR

Bundle bundle = this.getArguments();
if (bundle != null) {
    model = bundle.getParcelable("SectionDataModels");
}

You can keep the arraylist in your application class instead of first activity (as it would be same throughout the app), then simply pass the clicked item's position from activty1 to activity2 using intent1.putExtra("position",position) .

In activity 2 get the position using

int position = getIntent().getIntExtra("position")

Now simply get the model class object from the application class arraylist using this position.

您可以使ArrayList成为公共静态对象,然后在第二个活动中将其导入

it all depends on the size of the list.

you could also create a parcelable class with and arraylist, and send it to your second activity.

[1] Android Class Parcelable with ArrayList

[2] Android: How to pass Parcelable object to intent and use getParcelable method of bundle?

为了简化操作,您可以将其转换为json字符串格式,然后再次将其转换回您设置的模型对象列表,并按意图将其作为捆绑字符串传递给您,您可以使用GSON库对两者进行简单解析json格式和对象模型。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM