Is it all possible to access an adapter's data via another adapter?
I want to start an activity and pass data from an adapter to a fragment which is used in TabLayout as one of three fragments, I have two adapters and a button which is clicked to start an activity, its Java code is in my first adapter and I need to pass second adapter's data via second adapter itself
here is my codes:
my first adapter:
public class RecyclerViewDataAdapter extends RecyclerView.Adapter<RecyclerViewDataAdapter.ItemRowHolder>{
private ArrayList<SectionDataModel> dataList;
private Context mContext;
private RecyclerView.RecycledViewPool recycledViewPool;
private SnapHelper snapHelper;
public RecyclerViewDataAdapter(ArrayList<SectionDataModel> dataList, Context mContext) {
this.dataList = dataList;
this.mContext = mContext;
recycledViewPool = new RecyclerView.RecycledViewPool();
}
#Override
public ItemRowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, null);
ItemRowHolder rowHolder = new ItemRowHolder(v);
snapHelper = new GravitySnapHelper(Gravity.START);
return rowHolder;
}
#Override
public void onBindViewHolder(ItemRowHolder holder, int position) {
ArrayList singleSectionItems = dataList.get(position).getAllItemInSection();
final String sectionName = dataList.get(position).getHeaderTitle();
holder.itemTitle.setText(sectionName);
SectionDataAdapter adapter = new SectionDataAdapter(singleSectionItems, mContext);
holder.recyclerView.setHasFixedSize(true);
holder.recyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
holder.recyclerView.setAdapter(adapter);
holder.recyclerView.setRecycledViewPool(recycledViewPool);
snapHelper.attachToRecyclerView(holder.recyclerView);
holder.btnMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//here i can start the activity but..(second adapter)
Toast.makeText(view.getContext(), sectionName, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return (null != dataList ? dataList.size() : 0);
}
public class ItemRowHolder extends RecyclerView.ViewHolder {
protected ImageView mitemImage;
protected TextView mitemtext;
protected TextView itemTitle;
protected RecyclerView recyclerView;
protected Button btnMore;
public ItemRowHolder(View itemView) {
super(itemView);
this.mitemImage = itemView.findViewById(R.id.itemImage);
this.mitemtext = itemView.findViewById(R.id.tvTitle);
this.itemTitle = itemView.findViewById(R.id.itemTitle);
this.recyclerView = itemView.findViewById(R.id.recycler_view_list);
this.btnMore = itemView.findViewById(R.id.btnMore);
}
}
} '
and my second adapter:
import java.net.PortUnreachableException;
import java.util.ArrayList;
public class SectionDataAdapter extends RecyclerView.Adapter<SectionDataAdapter.SssingleItemRowHolder>{
private ArrayList<SingleItemModel> itemModels;
private Context mContext;
public SectionDataAdapter(ArrayList<SingleItemModel> itemModels, Context mContext) {
this.itemModels = itemModels;
this.mContext = mContext;
}
#Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_single_card, null);
SingleItemRowHolder singleItemRowHolder = new SingleItemRowHolder(v);
return singleItemRowHolder;
}
#Override
public void onBindViewHolder(SingleItemRowHolder holder, int position) {
SingleItemModel itemModel = itemModels.get(position);
holder.tvTitle.setText(itemModel.getName());
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(View itemView) {
super(itemView);
final Intent intent = new Intent(mContext,MainActivity.class);
this.mitemImage = itemView.findViewById(R.id.itemImage);
this.tvTitle = itemView.findViewById(R.id.tvTitle);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//... need to start the activity from here
Toast.makeText(view.getContext(), tvTitle.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
Like #MilaDroid said you simply need a getter that returns the another Adapter's ArrayList<SingleItemModel> but the problem you will face is that you need to have the same instance of the Adapter from the Activity in order to get the populated ArrayList<SingleItemModel>.
A good workaround is to used Bill Pugh's Singleton in the Adapter
public class Adapter {
private ArrayList<SingleItemModel> list;
private Adapter() {}
public static Adapter getInstance() {
return InstInit.INSTANCE;
}
// Don't forget to set the list (or NPE)
// because we can't argue with a Singleton
public void setList(ArrayList<SingleItemModel> list) {
this.list = list;
}
// You can now get the ArrayList
public ArrayList<SingleItemModel> getList() {
return list;
}
private static class InstInit {
private static final Adapter INSTANCE = new Adapter();
}
// Overrided RecyclerView.Adapter Methods
.................
}
Retrieving the ArrayList assuming that the following Adapters are Singleton
AdapterOne a1 = AdapterOne.getInstance();
AdapterTwo a2 = AdapterTwo.getInstance();
ArrayList<SingleItemModel> a1RetrievedList = a1.getList();
// You don't need to create a new instance
// creating a new instance doesn't make sense
// because you need to repopulate the list
// for the new instance.
ArrayList<SingleItemModel> a2RetrievedList = a2.getList();
// You can also retrieve from AdapterTwo
Related
I am adding data into an addToSepetims arraylist and I want to use it in another fragment but I cant get this arraylist
public class productAdapter extends RecyclerView.Adapter<productAdapter.ViewHolder> {
ArrayList<product_bilgileri> product_bilgileris = new ArrayList<product_bilgileri>();
LayoutInflater layoutInflater;
Context context;
ArrayList<AddToSepetim> addToSepetims = new ArrayList<AddToSepetim>();
public productAdapter(ArrayList<product_bilgileri> product_bilgileris, Context context) {
this.product_bilgileris = product_bilgileris;
this.context = context;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.productName.setText(product_bilgileris.get(position).getProductname());
holder.description.setText(product_bilgileris.get(position).getDescription());
holder.imageView.setImageDrawable(context.getResources().getDrawable(product_bilgileris.get(position).getImage()));
holder.ratingBar.setRating((product_bilgileris.get(position).getRating()));
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String a =holder.productName.getText().toString();
String b =holder.description.getText().toString();
int c = R.drawable.iphone5;
//Toast.makeText(context, ""+a, Toast.LENGTH_SHORT).show();
addToSepetims.add(new AddToSepetim(a,b,c));
}
});
}
This is Where I want to use addToSepetims arraylist :
public class SepetimFragment extends Fragment {
RecyclerView recyclerView;
ArrayList<AddToSepetim> addToSepetims = new ArrayList<AddToSepetim>();
public SepetimFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_sepetim, container, false);
recyclerView = view.findViewById(R.id.products_recylerview);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
SepetimAdapter sepetimAdapter = new SepetimAdapter(addToSepetims,getActivity());
recyclerView.setAdapter(sepetimAdapter);
return view;
}
}
I have also SepetimAdapter Class
public class SepetimAdapter extends RecyclerView.Adapter<SepetimAdapter.ViewHolder> {
ArrayList<AddToSepetim> addToSepetims = new ArrayList<AddToSepetim>();
LayoutInflater layoutInflater;
public SepetimAdapter(ArrayList<AddToSepetim> addToSepetims, Context context) {
this.addToSepetims = addToSepetims;
this.context = context;
}
Context context;
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.row_product_sepetim,parent,false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.productName.setText(addToSepetims.get(position).getProductname());
holder.description.setText(addToSepetims.get(position).getDescription());
holder.imageView.setImageDrawable(context.getResources().getDrawable(addToSepetims.get(position).getImage()));
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// addToSepetims.remove(addToSepetims.get(position));
}
});
}
#Override
public int getItemCount() {
return addToSepetims.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView productName,description;
ImageView imageView;
Button button;
public ViewHolder(#NonNull View itemView) {
super(itemView);
productName = itemView.findViewById(R.id.product_Name);
description = itemView.findViewById(R.id.descripton);
imageView = itemView.findViewById(R.id.product_pic);
button = itemView.findViewById(R.id.deleteFromCard);
}
}
}
Second QUESTION :
Product adapter class in onBindViewHolder class :
int c = R.drawable.iphone5;
in this line I want to get holder.imageView instead of "R.drawable.iphone5"
How can I do that ?
You can share data between fragments through a ViewModel:
Add dependency in build.gradle (Module:app) level.
implementation "androidx.lifecycle:lifecycle-viewmodel:2.2.0"
implementation "android.arch.lifecycle:runtime:2.2.0"
Create a custom ViewModel class that extends from AndroidViewModel
Here added the list you want to be shared between fragments.
public class MainViewModel extends AndroidViewModel {
private ArrayList<product_bilgileri> products;
public TempViewModel(#NonNull Application application) {
super(application);
}
public ArrayList<product_bilgileri> getProducts() {
return products;
}
public void setProducts(ArrayList<product_bilgileri> products) {
this.products = products;
}
}
Instantiate the ViewModel instance in activity/fragment
// In activity
MainViewModel mViewModel = new ViewModelProvider(this).get(MainViewModel.class);
// In fragment
MainViewModel mViewModel = new ViewModelProvider(requireActivity()).get(MainViewModel.class);
Then set the list of data with mViewModel.setProducts(myList) and retrieve it with mViewModel.getProducts()
For more info, check the documentation. Also check this article.
I try to pass data from an adapter to an activity and display it in a recyclerview. I am getting the NullPointerException when I run the app. What am I doing wrong?
This is the activity where I want to display data:
public class ListOfChatsActivity extends AppCompatActivity {
Toolbar lToolbar;
RecyclerView lRV;
BottomNavigationView lBnv;
ListOfChatsAdapter adapter;
LinearLayoutManager layoutManager;
ArrayList<String> chatList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_of_chats);
lToolbar = findViewById(R.id.lToolbar);
lRV = findViewById(R.id.lRV);
lBnv = findViewById(R.id.lBnv);
Intent intent = this.getIntent();
if(intent!=null){
String string = intent.getStringExtra("username");
chatList.add(string);}
adapter = new ListOfChatsAdapter(chatList, getApplicationContext());
layoutManager = new LinearLayoutManager(getApplicationContext());
lRV.setAdapter(adapter);
lRV.setLayoutManager(layoutManager);
}
This is the adapter from where I want to send data:
public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.ViewHolder> {
ArrayList<User> friendsSearchedList = new ArrayList<>();
Context mContext;
public SearchAdapter(ArrayList<User> friendsSearchedList, Context mContext){
this.friendsSearchedList = friendsSearchedList;
this.mContext = mContext;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.search_user_item,
parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
final User username = friendsSearchedList.get(position);
holder.text.setText(username.getUsername());
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String iUsername = holder.text.getText().toString();
Intent intent = new Intent();
intent.putExtra("username", iUsername);
}
});
}
#Override
public int getItemCount() {
return friendsSearchedList == null ? 0:friendsSearchedList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView text;
Button button;
RelativeLayout relativeLayout;
public ViewHolder(View itemView){
super(itemView);
text = itemView.findViewById(R.id.sText);
button = itemView.findViewById(R.id.addFriend);
relativeLayout = itemView.findViewById(R.id.relativeLayout);
}
}
}
I don't open the Activity from this Adapter. I just want to send extras. I tried more options, but I don't get it right.
Change 1
adapter = new ListOfChatsAdapter(chatList, getApplicationContext());
Why is the ListOfChatsAdapter being used here? You have included SearchAdapter as the adapter to use in the RecyclerView.
Change 2
The ViewHolder object that is returned by onCreateViewHolder(), should be of type SearchAdapter.ViewHolder and not just ViewHolder. The same applies to the first arguement of onBindViewHolder().
Try these and check
I am trying to reuse firebase adapter in two activities with different onClick Listener behaviors depending on both activities.
Here is the code:
public class ProductListAdapter {
private Query mQuery;
private Context mContext;
private FirebaseRecyclerAdapter<Product,ProductViewHolder> mAdapter;
public ProductListAdapter(Query query,Context context) {
mQuery = query;
mContext = context;
Update();
}
public void Update(){
mAdapter = new FirebaseRecyclerAdapter<Product, ProductViewHolder>(
Product.class,
R.layout.list_item_product,
ProductViewHolder.class,
mQuery
){
#Override
protected void populateViewHolder(ProductViewHolder viewHolder, Product model, int position) {
viewHolder.mProductTitle.setText(model.getProductTitle());
viewHolder.mProductDescription.setText(model.getProductDescription());
Product product = getItem(position);
viewHolder.bindView(product);
Picasso.with(mContext)
.load(model.getPhotoUrl())
.into(viewHolder.mThumbnail);
}
};
}
public RecyclerView.Adapter getAdapter(){
return mAdapter;
}
public static class ProductViewHolder extends RecyclerView.ViewHolder{
Product mProduct;
TextView mProductTitle;
TextView mProductDescription;
ImageView mThumbnail;
public ProductViewHolder(View itemView) {
super(itemView);
mProductTitle = (TextView) itemView.findViewById(R.id.product_title);
mProductDescription = (TextView) itemView.findViewById(R.id.product_description);
mThumbnail = (ImageView) itemView.findViewById(R.id.list_image);
}
public void bindView(Product product){
mProduct = product;
}
}
And This is the code in calling activity which calls the firebaseadapter class, The class is returning an adapter using getAdapter Method and which is given to recycler view:
ProductListAdapter productListAdapter =
new ProductListAdapter(query,getActivity());
RecyclerView.Adapter adapter = productListAdapter.getAdapter();
mRecyclerView.setAdapter(adapter);
You can set onClickListinner() in any element inside your viewHolder
Try something like that:
if (condition) {
viewHolder.mThumbnail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
... doStuff
}
});
} else {
viewHolder.mThumbnail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
... doOtherStuff
}
});
}
About the reuse, it is best to creat a class which extends FirebaseRecyclerAdapter, and them inside it define the method populateViewHolder, having this condition for each OnClickListener.
As a example:
public class RecipeAdapter extends FirebaseRecyclerAdapter<Product, ProductViewHolder>{
private static final String TAG = RecipeAdapter.class.getSimpleName();
private Context context;
public RecipeAdapter(Class<Product> modelClass, int modelLayout, Class<ProductViewHolder> viewHolderClass, DatabaseReference ref, Context context) {
super(modelClass, modelLayout, viewHolderClass, ref);
this.context = context;
}
#Override
protected void populateViewHolder(ProductViewHolder viewHolder, Product model, int position) {
...
}
}
And then set the adapter:
mAdapter = new RecipeAdapter<Product, ProductViewHolder>(
Product.class,
R.layout.list_item_product,
ProductViewHolder.class,
mQuery,
this
)
I have made a horizontal recyclerview inside a fragment. Now when I click on any item I don't see the on click listener working. Here is my code for the Adapter class:
public class FeaturedProductsAdapter extends RecyclerView.Adapter<FeaturedProductsAdapter.CustomViewHolder> {
private List<FeaturedProductInfo> feedItemList;
private Context mContext;
public FeaturedProductsAdapter(Context context, List<FeaturedProductInfo> feedItemList) {
this.feedItemList = feedItemList;
this.mContext = context;
}
public class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected ImageView imageView;
protected TextView textView,priceView;
private Context context;
public CustomViewHolder(View view,Context context) {
super(view);
this.context=context;
this.imageView = (ImageView) view.findViewById(R.id.thumbnail);
this.textView = (TextView) view.findViewById(R.id.prodTitle);
this.priceView = (TextView) view.findViewById(R.id.prodPrice);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int position = getLayoutPosition(); // gets item position
Log.e("Check", position + "");
FeaturedProductInfo user = feedItemList.get(position);//[position];
// We can access the data within the views
Intent intent = new Intent(context, ProductDescription.class);
intent.putExtra("id", user.getId());
mContext.startActivity(intent);
}
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(mContext).inflate(R.layout.featured_product_list_item_card, null);
Context context = viewGroup.getContext();
CustomViewHolder viewHolder = new CustomViewHolder(view,context);
return viewHolder;
}
#Override
public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {
FeaturedProductInfo feedItem = feedItemList.get(i);
//Download image using picasso library
if(!feedItem.getUrl().contains("."))
{
feedItem.setUrl("nothing");
}
Picasso.with(mContext).load(feedItem.getUrl())
.error(R.drawable.unavailable)
.placeholder(R.drawable.unavailable)
.resize(110,110)
.into(customViewHolder.imageView);
//Setting text view title
customViewHolder.textView.setText(feedItem.getTitle());
customViewHolder.priceView.setText(feedItem.getPrice());
//Log.e("Featured: ","SET");
}
#Override
public int getItemCount() {
return (null != feedItemList ? feedItemList.size() : 0);
}
}
I think I am not getting how to use the view holder properly. While I have used the same code for recyclerView in another activities and it works like charm.
1.Simple Click Handler within ViewHolder
RecyclerView does not have special provisions for attaching click handlers to items unlike ListView which has the method setOnItemClickListener(). To achieve a similar effect, we can attach click events within the ViewHolder within our adapter:
public class ContactsAdapter extends RecyclerView.Adapter<ContactsAdapter.ViewHolder> {
// ...
// Used to cache the views within the item layout for fast access
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView tvName;
public TextView tvHometown;
private Context context;
public ViewHolder(Context context, View itemView) {
super(itemView);
this.tvName = (TextView) itemView.findViewById(R.id.tvName);
this.tvHometown = (TextView) itemView.findViewById(R.id.tvHometown);
// Store the context
this.context = context;
// Attach a click listener to the entire row view
itemView.setOnClickListener(this);
}
// Handles the row being being clicked
#Override
public void onClick(View view) {
int position = getLayoutPosition(); // gets item position
User user = users.get(position);
// We can access the data within the views
Toast.makeText(context, tvName.getText(), Toast.LENGTH_SHORT).show();
}
}
// ...
}
Another way is my preferred way.. but this is also a fine way to go about it.
My onBindViewHolder
#Override
public void onBindViewHolder(CategoryViewHolder holder, int position) {
Category category = mCategories.get(position);
holder.tvTitle.setText(category.getTitle());
holder.tvDescription.setText(category.getDescription());
holder.rlContainer.setOnClickListener(mClickListener);
holder.rlContainer.setTag(holder);
}
My class level (Adapter object of View.OnClickListner)
View.OnClickListener mClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
CategoryViewHolder holder = (CategoryViewHolder) view.getTag();
int position = holder.getAdapterPosition();
startAppointmentBookingFor(mCategories.get(position));
}
};
so basically attach the listener to any view in your holder (I try to put it on container only), then extract it out on the onclick and handle positions etc.
In ‘CustomViewHolder’ below ‘super(view)’ add
view.setOnClickListener(this)
You’re done
Should work.
Make the following changes to your Adapter:
public class FeaturedProductsAdapter extends RecyclerView.Adapter<FeaturedProductsAdapter.CustomViewHolder> {
private List<FeaturedProductInfo> feedItemList;
private Context mContext;
private OnItemClickListener onItemClickListener;
public FeaturedProductsAdapter(Context context, List<FeaturedProductInfo,OnItemClickListener onItemClickListener> feedItemList) {
this.feedItemList = feedItemList;
this.mContext = context;
this.onItemClickListener = onItemClickListener;
}
public class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected ImageView imageView;
protected TextView textView,priceView;
private Context context;
public CustomViewHolder(View view,Context context) {
super(view);
this.context=context;
this.imageView = (ImageView) view.findViewById(R.id.thumbnail);
this.textView = (TextView) view.findViewById(R.id.prodTitle);
this.priceView = (TextView) view.findViewById(R.id.prodPrice);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
onItemClickListener.onItemClick(getLayoutPosition());
Log.e("Check", position + "");
FeaturedProductInfo user = feedItemList.get(position);//[position];
// We can access the data within the views
Intent intent = new Intent(context, ProductDescription.class);
intent.putExtra("id", user.getId());
mContext.startActivity(intent);
}
}
public interface OnItemClickListener{
void onItemClick(int position);
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(mContext).inflate(R.layout.featured_product_list_item_card, null);
Context context = viewGroup.getContext();
CustomViewHolder viewHolder = new CustomViewHolder(view,context);
return viewHolder;
}
#Override
public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {
FeaturedProductInfo feedItem = feedItemList.get(i);
//Download image using picasso library
if(!feedItem.getUrl().contains("."))
{
feedItem.setUrl("nothing");
}
Picasso.with(mContext).load(feedItem.getUrl())
.error(R.drawable.unavailable)
.placeholder(R.drawable.unavailable)
.resize(110,110)
.into(customViewHolder.imageView);
//Setting text view title
customViewHolder.textView.setText(feedItem.getTitle());
customViewHolder.priceView.setText(feedItem.getPrice());
//Log.e("Featured: ","SET");
}
#Override
public int getItemCount() {
return (null != feedItemList ? feedItemList.size() : 0);
}
I have an activity with the following code and I am trying to update the data from IntentService by creating the instance of the class and calling the method to update but it's crashing with a null pointer exception at mAdapter. Is this the right way to pass data from IntentService to an activity?
COde:
public class MainActivity extends Activity {
RecyclerView rv;
SimpleStringRecyclerViewAdapter mAdapter;
public static final TypedValue mTypedValue = new TypedValue();
public static int mBackground;
public static List<String> mValues;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cheesecake_homepage_fragment_cheese_list);
rv = (RecyclerView) findViewById(R.id.recyclerview);
setupRecyclerView(rv);
send_msg("");
}
public void setupRecyclerView(RecyclerView recyclerView) {
mAdapter = new SimpleStringRecyclerViewAdapter(getBaseContext(),
getRandomSublist(Cheeses.sCheeseStrings, 3));
recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
recyclerView.setAdapter(mAdapter);
}
private List<String> getRandomSublist(String[] array, int amount) {
ArrayList<String> list = new ArrayList<>(amount);
Random random = new Random();
while (list.size() < amount) {
list.add(array[random.nextInt(array.length)]);
}
return list;
}
public static class SimpleStringRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleStringRecyclerViewAdapter.ViewHolder> {
public static class ViewHolder extends RecyclerView.ViewHolder {
public String mBoundString;
public final View mView;
public final ImageView mImageView;
public final TextView mTextView;
public ViewHolder(View view) {
super(view);
mView = view;
mImageView = (ImageView) view.findViewById(R.id.avatar);
mTextView = (TextView) view.findViewById(android.R.id.text1);
}
#Override
public String toString() {
return super.toString() + " '" + mTextView.getText();
}
}
public String getValueAt(int position) {
return mValues.get(position);
}
public SimpleStringRecyclerViewAdapter(Context context, List<String> items) {
context.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true);
mBackground = mTypedValue.resourceId;
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cheesecake_homepage_list_item, parent, false);
view.setBackgroundResource(mBackground);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mBoundString = mValues.get(position);
holder.mTextView.setText(mValues.get(position));
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
/*Intent intent = new Intent(context, CheeseDetailActivity.class);
intent.putExtra(CheeseDetailActivity.EXTRA_NAME, holder.mBoundString);
context.startActivity(intent);*/
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
}
public void send_msg( String set_text){
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
List<String> uu = getRandomSublist(Cheeses.sCheeseStrings, 1);
mValues.addAll(uu);
mAdapter.notifyDataSetChanged();
}
});
}
}
In intent service:
MainActivity test = new MainActivity();
test.send_msg("");
You can not use MainActivity instance like that in your Intent service code.
There are multiple approach to update UI from service like, LocalBroadcastReceivers, Messengers, BoundedService etc.
You can find an example to update UI from service using LocalBroadcastManager here
update data from intentservice on an activity
By creating Object of class which is extending Activity or any other main application component is not right way for communication between components.
For with in process communication(as in your case want to send data from IntentService to Activity) use LocalBroadcastManager