When you click on the CardView, a DialogFragment should appear, but the application crashes, writes the following in the logs
Process: com.example.testfuntura, PID: 15385
java.lang.ClassCastException: android.view.ContextThemeWrapper cannot be cast to androidx.appcompat.app.AppCompatActivity
at com.example.testfuntura.Attraction.AdapterAttractionsPackageOffer.lambda$onBindViewHolder$0(AdapterAttractionsPackageOffer.java:56)
at com.example.testfuntura.Attraction.-$$Lambda$AdapterAttractionsPackageOffer$4cZEQxk2beWA40yZmNkr6ZJp7o8.onClick(lambda)
at android.view.View.performClick(View.java:5692)
at android.view.View$PerformClick.run(View.java:22596)
My Adapter
public class AdapterAttractionsPackageOffer extends RecyclerView.Adapter<AdapterAttractionsPackageOffer.AttractionsViewHolderPackageOffer> {
public ArrayList<ItemPOA> mFavList;
public AdapterAttractionsPackageOffer(ArrayList<ItemPOA> favList) {
mFavList = favList;
}
#NonNull
#Override
public AttractionsViewHolderPackageOffer onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_attraction_package_offer, parent, false);
return new AttractionsViewHolderPackageOffer(v);
}
public static class AttractionsViewHolderPackageOffer extends RecyclerView.ViewHolder {
public ImageView card_image_1;
public TextView Package_offer_title;
public CardView Card;
public AttractionsViewHolderPackageOffer(View itemView) {
super(itemView);
Card = itemView.findViewById(R.id.att_po);
card_image_1 = itemView.findViewById(R.id.img_po);
Package_offer_title = itemView.findViewById(R.id.tex);
}
}
#SuppressLint("LongLogTag")
#Override
public void onBindViewHolder(AttractionsViewHolderPackageOffer holder, int position) {
ItemPOA currentItem = mFavList.get(position);
holder.Package_offer_title.setText(currentItem.get_Package_offer_title());
holder.Card.setOnClickListener(v -> {
DialogPOA dialog = new DialogPOA();
dialog.show(((AppCompatActivity) v.getContext()).getSupportFragmentManager(), "item");
Bundle bundle1 = new Bundle();
bundle1.putString("title_po", currentItem.get_Package_offer_title());
bundle1.putString("description_po", currentItem.get_Package_offer_description());
bundle1.putString("cost_po", currentItem.get_Package_offer_cost());
dialog.setArguments(bundle1);
});
holder.getAdapterPosition();
}
#Override
public int getItemCount() {
return mFavList.size();
}
}
I have a similar Adapter, but when called, everything works, that is, the problem is not in the DialogFragment, since everything works when called from another fragment.
Fragment that the CardView is in
public class FragmentAtt extends Fragment {
ArrayList<ItemPOA> mFavList;
String URL = "http://qqqqqqqqq.mcdir.ru/dbpo.php";
RecyclerView mRec;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
//ImageView GET_PO_IMG;
String GET_PO_TITLE = "title_po";
String GET_PO_DESCRIPTION = "description_po";
String GET_PO_COST = "cost_po";
RequestQueue requestQueue;
JsonArrayRequest jsonArrayRequest;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_test_attraction, container, false);
TabLayout tabLayout = view.findViewById(R.id.tab);
ViewPager viewPager = view.findViewById(R.id.pager);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
return view;
}
#Override
public void onViewCreated(#NonNull final View view, #Nullable Bundle savedInstanceState) {
mRec = requireView().findViewById(R.id.rec_po);
mFavList = new ArrayList<>();
recyclerViewadapter = new AdapterAttractionsPackageOffer(mFavList);
recyclerViewlayoutManager = new LinearLayoutManager(getContext());
mRec.setHasFixedSize(true);
mRec.setLayoutManager(recyclerViewlayoutManager);
mRec.setAdapter(recyclerViewadapter);
JSON_DATA_WEB_CALL2_RINK();
//recyclerViewlayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
//SnapHelper snapHelper = new GravitySnapHelper(Gravity.START);
//snapHelper.attachToRecyclerView(mRec);
}
private void setupViewPager(ViewPager viewPager) {
PagerAdapter adapter = new PagerAdapter(getChildFragmentManager());
adapter.addFragment(new FragmentAttractionRecyclerView(), "Аттракционы");
adapter.addFragment(new FragmentAttractionRecyclerView(), "Видеоигры");
viewPager.setAdapter(adapter);
}
public void JSON_DATA_WEB_CALL2_RINK() {
jsonArrayRequest = new JsonArrayRequest(URL,
this::JSON_PARSE_DATA_AFTER_WEBCALL_RINK,
error ->
Log.e("Volley", error.toString())) {
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
try {
Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(response);
if (cacheEntry == null) {
cacheEntry = new Cache.Entry();
}
final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely
long now = System.currentTimeMillis();
final long ttl = now + cacheExpired;
cacheEntry.data = response.data;
cacheEntry.softTtl = now;
cacheEntry.ttl = ttl;
String headerValue;
headerValue = response.headers.get("Date");
if (headerValue != null) {
cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
}
headerValue = response.headers.get("Last-Modified");
if (headerValue != null) {
cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue);
}
cacheEntry.responseHeaders = response.headers;
final String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONArray(jsonString), cacheEntry);
} catch (UnsupportedEncodingException | JSONException e) {
return Response.error(new ParseError(e));
}
}
};
requestQueue = Volley.newRequestQueue(requireContext());
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL_RINK(JSONArray array) {
mFavList.clear();
for (int i = 0; i < array.length(); i++) {
ItemPOA GetDataAdapter2 = new ItemPOA();
JSONObject json;
try {
json = array.getJSONObject(i);
GetDataAdapter2.set_Package_offer_title(json.getString(GET_PO_TITLE));
GetDataAdapter2.set_Package_offer_description(json.getString(GET_PO_DESCRIPTION));
GetDataAdapter2.set_Package_offer_cost(json.getString(GET_PO_COST));
} catch (JSONException e) {
e.printStackTrace();
}
mFavList.add(GetDataAdapter2);
}
recyclerViewadapter = new AdapterAttractionsPackageOffer(mFavList);
mRec.setAdapter(recyclerViewadapter);
}
}
An Adapter that has the same functionality, but why does it work, explain the difference?
public class AdapterSkatingRinkSchedule_2 extends RecyclerView.Adapter<AdapterSkatingRinkSchedule_2.SkatingRinkScheduleViewHolder> {
public ArrayList<ItemSkatingRinkSchedule_2> mSkatingRinkScheduleList;
public AdapterSkatingRinkSchedule_2(ArrayList<ItemSkatingRinkSchedule_2> SkatingRinkScheduleList) {
mSkatingRinkScheduleList = SkatingRinkScheduleList;
}
#NonNull
#Override
public SkatingRinkScheduleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_srs, parent, false);
return new SkatingRinkScheduleViewHolder(v);
}
public static class SkatingRinkScheduleViewHolder extends RecyclerView.ViewHolder {
public TextView number_srs, start_time_srs, end_time_srs, cost_1_srs, cost_2_srs;
public LinearLayout ll_main;
public SkatingRinkScheduleViewHolder(View itemView) {
super(itemView);
ll_main = itemView.findViewById(R.id.ll_main);
number_srs = itemView.findViewById(R.id.number_srs);
start_time_srs = itemView.findViewById(R.id.start_time_srs);
end_time_srs = itemView.findViewById(R.id.end_time_srs);
cost_1_srs = itemView.findViewById(R.id.cost_1_srs);
cost_2_srs = itemView.findViewById(R.id.cost_2_srs);
}
}
#SuppressLint("LongLogTag")
#Override
public void onBindViewHolder(SkatingRinkScheduleViewHolder holder, int position) {
ItemSkatingRinkSchedule_2 currentItem = mSkatingRinkScheduleList.get(position);
holder.number_srs.setText(currentItem.get_session_number());
holder.start_time_srs.setText(currentItem.get_session_start());
holder.end_time_srs.setText(currentItem.get_session_end());
holder.cost_1_srs.setText(currentItem.get_weekdays());
holder.cost_2_srs.setText(currentItem.get_weekends_and_holidays());
holder.ll_main.setOnClickListener(v -> {
DialogSkatingRinkSchedule dialogSRS = new DialogSkatingRinkSchedule();
dialogSRS.show(((AppCompatActivity) v.getContext()).getSupportFragmentManager(), "item");
Bundle bundle2 = new Bundle();
bundle2.putString("number", currentItem.get_session_number());
bundle2.putString("start", currentItem.get_session_start());
bundle2.putString("end", currentItem.get_session_end());
bundle2.putString("w", currentItem.get_weekdays());
bundle2.putString("wah", currentItem.get_weekends_and_holidays());
dialogSRS.setArguments(bundle2);
});
holder.getAdapterPosition();
}
#Override
public int getItemCount() {
return mSkatingRinkScheduleList.size();
}
}
java.lang.ClassCastException: android.view.ContextThemeWrapper cannot be cast to androidx.appcompat.app.AppCompatActivity
Here you are casting a context to an AppCompatActivity but actually Activity is not a Context
You have two options to solve this:
First option: Create a listener interface between the activity/fragment that holds the RecyclerView, implement it in that activity, and trigger its callback within the CardView onClickListener onClick() callback.
Second option: Change the constructor signature of the AdapterAttractionsPackageOffer adapter to accept a FragmentManager instance; save it as a class field like below, and reflect that on the instantiation of the adapter
public class AdapterAttractionsPackageOffer extends RecyclerView.Adapter<AdapterAttractionsPackageOffer.AttractionsViewHolderPackageOffer> {
public ArrayList<ItemPOA> mFavList;
private FragmentManager fragmentMgr;
public AdapterAttractionsPackageOffer(ArrayList<ItemPOA> favList, FragmentManager fManger) {
mFavList = favList;
fragmentMgr = fManger;
}
//......... suppressed code
#SuppressLint("LongLogTag")
#Override
public void onBindViewHolder(AttractionsViewHolderPackageOffer holder, int position) {
ItemPOA currentItem = mFavList.get(position);
holder.Package_offer_title.setText(currentItem.get_Package_offer_title());
holder.Card.setOnClickListener(v -> {
DialogPOA dialog = new DialogPOA();
dialog.show(fragmentMgr, "item");
Bundle bundle1 = new Bundle();
bundle1.putString("title_po", currentItem.get_Package_offer_title());
bundle1.putString("description_po", currentItem.get_Package_offer_description());
bundle1.putString("cost_po", currentItem.get_Package_offer_cost());
dialog.setArguments(bundle1);
});
holder.getAdapterPosition();
}
//......... suppressed code
}
Related
i want create a fragment and have inside a recycler view for show products ...
but when i render it is show this error : RecyclerView: No adapter attached; skipping layout
below i copy my codes;
this code is for adapter class :
private ArrayList<Products> ProductsList;
private Context context;
public Adapter(ArrayList<Products> productsList, Context context) {
ProductsList = productsList;
this.context = context;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.row_layout, parent, false);
return new MyHolder(v);
}
#Override
public void onBindViewHolder(MyHolder holder, final int position) {
Products products = ProductsList.get(position);
holder.txtName.setText(products.getName());
holder.txtPrice.setText("$ " + products.getPrice());
Picasso.get().load(Config.ipValue + "/images/" + products.getPhoto()).into(holder.imgV);
holder.imgV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.startAnimation(AnimationUtils.loadAnimation(context, android
.R.anim.slide_in_left));
}
});
}
#Override
public int getItemCount() {
return ProductsList.size();
}
class MyHolder extends RecyclerView.ViewHolder {
TextView txtName;
TextView txtPrice;
ImageView imgV;
public MyHolder(View itemView) {
super(itemView);
txtName = itemView.findViewById(R.id.rowTxtProductName);
txtPrice = itemView.findViewById(R.id.rowTxtPrice);
imgV = itemView.findViewById(R.id.rowImgProduct);
}
}
and this one for web api class :
public class WebApiHandler {
Context context;
String apiLink = "";
ArrayList<Products> products = new ArrayList<>();
public WebApiHandler(Context context) {
this.context = context;
}
void apiConnect(String type) {
switch (type) {
case "getproducts": {
apiLink = Config.getProductsWebApi;
break;
}
}
ProgressDialog dialog = ProgressDialog.show(context, "Connecting...",
"please wait", false, false);
StringRequest request = new StringRequest(Request.Method.POST,
apiLink, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
dialog.dismiss();
showJson(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
}
});
RequestQueue queue = Volley.newRequestQueue(context);
queue.add(request);
}
private void showJson(String response) {
products.clear();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String id = object.getString("id");
String name = object.getString("name");
String description = object.getString("description");
String price = object.getString("price");
String photo = object.getString("photo");
Products p = new Products(id, name, description, price, photo);
products.add(p);
}
} catch (JSONException e) {
e.printStackTrace();
}
VerticalFragment.productsArrayList = products;
IData iData = (IData) context;
iData.sendData();
}}
and my fragment code :
public class VerticalFragment extends Fragment implements IData {
RecyclerView rcVertical;
WebApiHandler webApiHandler;
static ArrayList<Products> productsArrayList = new ArrayList<>();
public VerticalFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_vertical, container, false);
rcVertical = view.findViewById(R.id.rcVertical);
webApiHandler = new WebApiHandler(getContext());
webApiHandler.apiConnect("getproducts");
rcVertical.addOnItemTouchListener(new RecyclerTouchListener(getContext(), rcVertical,
new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
ProductActivity.products = productsArrayList.get(position);
startActivity(new Intent(getContext(), ProductActivity.class));
}
#Override
public void onLongClick(View view, int position) {
}
}));
return view;
}
#Override
public void sendData() {
Adapter adapter = new Adapter(productsArrayList, getContext());
rcVertical.setLayoutManager(new LinearLayoutManager((getContext())));
rcVertical.setItemAnimator(new DefaultItemAnimator());
rcVertical.setAdapter(adapter);
}}
i should say i create a interface and have one method i say it sendData
This is a common error when there is no adapter attached to recyclerview upon showing recyclerview. It will not cause any harm to your app, but you could avoid it by setting empty adapter without data, and later when you get your data, provide it to your adapter and notify it
Edit - Example added
Create setter for your list in adapter. After that, in your fragment make adapter global and in onCreateView make instance of your adapter and attach it to recyclerview
adapter = new Adapter(new ArrayList<>(), getContext());
rcVertical.setAdapter(adapter);
...Initialize recyclerview...
And then in your sendData interface put your loaded values in it
adapter.setData(productsArrayList);
adapter.notifyDataSetChanged();
I am trying to implement AdMobs to load ads, every 5th row but i am having a difficult time, as you can see from my screenshot ads are being loaded successfully but they're being loaded after every row. Can someone help me accomplish this? I already tried reading through post on stack overflow but none seems to help. Thank you in advance. image screenshot
Fragment
public class SectorPerformanceFragment extends Fragment {
private RecyclerView newsFeedRecycleView;
private SectorPerformanceAdapter mostActiveAdapter;
private RecyclerViewAdopter recyclerViewAdopter;
public static final int ITEMS_PER_AD = 9;
private RecyclerView.LayoutManager layoutManager;
private RequestQueue requestQueue;
private JSONObject stockDetails;
public static ArrayList<SectorPerformanceModel> mostActiveArrayList;
private RequestQueue requestQueues;
private ImageView backImage;
private View rootView;
private ProgressBar loadingProgressBar;
private TextView sectorNameTv;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.recycle_view_list_ui, container, false);
sectorNameTv = rootView.findViewById(R.id.sectorNameTv);
sectorNameTv.setText("Sector Performance");
loadingProgressBar = rootView.findViewById(R.id.loadingProgressBar);
backImage = rootView.findViewById(R.id.backImageView);
backImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().popBackStack();
//
// Fragment generalMarketFragment = new BrowseFragment();
// FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
// FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// fragmentTransaction.replace(R.id.fragment_container, generalMarketFragment);
// fragmentTransaction.addToBackStack(null);
// fragmentTransaction.commit();
}
});
requestQueues = Volley.newRequestQueue(getActivity());
findViewById();
mostActiveArrayList = new ArrayList<>();
initRecycleView();
retreiveBundleInformation();
return rootView;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
private void findViewById() {
newsFeedRecycleView = rootView.findViewById(R.id.recylcle_view_list);
}
//set up RecycleVIew/listener to detect taps layout manager tels recycle view how to display the list.. without it, nothing shows up
public void initRecycleView() {
layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
newsFeedRecycleView.setHasFixedSize(true);
newsFeedRecycleView.setLayoutManager(layoutManager);
//mostActiveAdapter = new SectorPerformanceAdapter(getContext(), mostActiveArrayList);
// recyclerViewAdopter = new RecyclerViewAdopter(getContext(),mostActiveArrayList);
//
// //newsFeedRecycleView.setAdapter(mostActiveAdapter);
// newsFeedRecycleView.setAdapter(recyclerViewAdopter);
}
//download news data stocknewsapi..
private void downloadStockList(String api) {
// Initialize a new JsonArrayRequest instance
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
Request.Method.GET,
api,
null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// Do something with response
//mTextView.setText(response.toString());
loadingProgressBar.setVisibility(View.INVISIBLE);
//Log.i("jsonResponse", response.toString());
// Process the JSON
// Loop through the array elements
for (int i = 0; i < response.length(); i++) {
// Get current json object
try {
stockDetails = response.getJSONObject(i);
Log.i("stockDetails", stockDetails.toString());
SectorPerformanceModel sectorPerformanceModel2 = new SectorPerformanceModel(stockDetails.getString("sector"),stockDetails.getString("changesPercentage"),1);
mostActiveArrayList.add((sectorPerformanceModel2));
SectorPerformanceModel sectorPerformanceModel3 = new SectorPerformanceModel(stockDetails.getString("sector"),stockDetails.getString("changesPercentage"),2);
mostActiveArrayList.add(mostActiveArrayList.size(),sectorPerformanceModel3);
recyclerViewAdopter = new RecyclerViewAdopter(getContext(),mostActiveArrayList);
//newsFeedRecycleView.setAdapter(mostActiveAdapter);
newsFeedRecycleView.setAdapter(recyclerViewAdopter);
//recyclerViewAdopter.notifyDataSetChanged();
// mostActiveArrayList.add(sectorPerformanceModel);
// mostActiveAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("error", error.toString());
}
}
);
// Add JsonArrayRequest to the RequestQueue
requestQueues.add(jsonArrayRequest);
}
public void retreiveBundleInformation() {
downloadStockList("APIKEY");
}
}
Adapter
[public class RecyclerViewAdopter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private Context mContext;
private List<SectorPerformanceModel> mList;
public RecyclerViewAdopter(Context mContext, List<SectorPerformanceModel> mList) {
this.mList = mList;
this.mContext = mContext;
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name;
private TextView newsTitle, sourceName, epsEstiatmate;
private CircleImageView newsThumbImage;
public MyViewHolder(View view) {
super(view);
epsEstiatmate = itemView.findViewById(R.id.formTypeTv);
newsTitle = itemView.findViewById(R.id.tickerTv);
sourceName = itemView.findViewById(R.id.dateTv);
newsThumbImage= itemView.findViewById(R.id.defaultImageColor);
newsThumbImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("tapped","TAPPED");
}
});
}
}
public static class ViewHolderAdMob extends RecyclerView.ViewHolder {
public AdView mAdView;
public ViewHolderAdMob(View view) {
super(view);
mAdView = (AdView) view.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
mAdView.loadAd(adRequest);
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch(viewType){
case 1:{
View v = inflater.inflate(R.layout.trending_stock_row, parent, false);
viewHolder = new MyViewHolder(v);
break;
}
case 2:{
View v = inflater.inflate(R.layout.ads_row, parent, false);
viewHolder = new ViewHolderAdMob(v);
break;
}
}
return viewHolder;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
SectorPerformanceModel model= mList.get(holder.getAdapterPosition());
switch(holder.getItemViewType()){
case 1:{
MyViewHolder viewHolder = (MyViewHolder) holder;
Random r = new Random();
int red = r.nextInt(255 - 0 + 1) + 0;
int green = r.nextInt(255 - 0 + 1) + 0;
int blue = r.nextInt(255 - 0 + 1) + 0;
GradientDrawable draw = new GradientDrawable();
draw.setShape(GradientDrawable.OVAL);
draw.setColor(Color.rgb(red, green, blue));
viewHolder.newsThumbImage.setBackground(draw);
viewHolder.newsTitle.setText(model.getSector());
viewHolder.sourceName.setText(model.getChangesPercentage());
break;
}
case 2:{
break;
}
}
}
#Override
public int getItemViewType(int position) {
return mList.get(position).getViewType();
}
#Override
public int getItemCount() {
return mList.size();
}
}][1]
It looks like you are adding 2 items to your adapter's data source for each element in your API response: one element has viewType 1 and the other viewType 2:
SectorPerformanceModel sectorPerformanceModel2 = new SectorPerformanceModel(stockDetails.getString("sector"),stockDetails.getString("changesPercentage"),1);
mostActiveArrayList.add((sectorPerformanceModel2));
SectorPerformanceModel sectorPerformanceModel3 = new SectorPerformanceModel(stockDetails.getString("sector"),stockDetails.getString("changesPercentage"),2);
mostActiveArrayList.add(mostActiveArrayList.size(),sectorPerformanceModel3);
Your adapter is rendering items with viewType 2 as ad rows, so if you want to display an ad row every 5 rows you'll need to update the downloadStockList method to execute this
SectorPerformanceModel sectorPerformanceModel3 = new SectorPerformanceModel(stockDetails.getString("sector"),stockDetails.getString("changesPercentage"),2);
mostActiveArrayList.add(mostActiveArrayList.size(),sectorPerformanceModel3);
only after having added 4 items with viewType 1.
I have an Fragment with recycleview where I populate it with json items from internet.
It load fine and Next step I want to is open new Activity when any row is clicked. It works in activity, thus I modified the same code for fragment but for fragment it throws exception in line
mExampleAdapter.setOnItemClickListener(getActivity());
with errror setOnItemClickListener of refrence adatper cannot be applied to Fragment activty and thus when I change line to
(ExampleAdapter.OnItemClickListener)
and when i build and run . Then app crashes with error that Mainactivity which holds framgnet cannot be cast in to .ExampleAdapter$OnItemClickListener
Here is my whole Fragment class
public class Mynotes extends Fragment implements ExampleAdapter.OnItemClickListener{
public static final String YTD_LINK = "link";
private RecyclerView mRecyclerView;
private ExampleAdapter mExampleAdapter;
private ArrayList<ExampleItem> mExampleList;
private RequestQueue mRequestQueue;
String url="https://api.myjson.com/bins/16mecx";
public Mynotes() {
}
#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.activity_jsonfeed, container, false);
mRecyclerView = view.findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.addItemDecoration(new MyDividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL, 36));
mExampleList = new ArrayList<>();
mExampleAdapter = new ExampleAdapter(getActivity(), mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
mExampleAdapter.setOnItemClickListener((ExampleAdapter.OnItemClickListener) getActivity());
parseJSON();
return view;
}
private void parseJSON() {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
myProgressBar.setVisibility(View.GONE);
try {
JSONArray jsonArray = response.getJSONArray("hits");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
String videoTitle = hit.getString("title");
String link = hit.getString("link");
mExampleList.add(new ExampleItem(videoTitle, link));
mExampleAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
#Override
public void onItemClick(int position) {
Intent intent = new Intent(getActivity(), NewActiviyt.class);
ExampleItem clickedItem = mExampleList.get(position);
intent.putExtra(YTD_LINK, clickedItem.getmLink());
startActivity(intent);
}
#Override
public void onRefresh() {
}
}
and my Adapter Class is
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private Context mContext;
private ArrayList<ExampleItem> mExampleList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public ExampleAdapter(Context context, ArrayList<ExampleItem> exampleList) {
mContext = context;
mExampleList = exampleList;
}
#Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.example_item, parent, false);
return new ExampleViewHolder(v);
}
#Override
public void onBindViewHolder(ExampleViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
String title = currentItem.getTitle();
// int likeCount = currentItem.getLikeCount();
// String imageUrl = currentItem.getImageUrl();
holder.mTextViewCreator.setText(title);
// holder.mTextViewLikes.setText("Likes: " + likeCount);
// Glide.with(mContext).load(imageUrl).apply(RequestOptions.circleCropTransform()).into(holder.mImageView);
}
#Override
public int getItemCount() {
return mExampleList.size();
}
public class ExampleViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView mTextViewCreator;
// public TextView mTextViewLikes;
// public ImageView mImageView;
public ExampleViewHolder(View itemView) {
super(itemView);
// mTextViewLikes = itemView.findViewById(R.id.text_view_likes);
// mImageView = itemView.findViewById(R.id.image_view);
mTextViewCreator = itemView.findViewById(R.id.text_title);
}
#Override
public void onClick(View view) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
}
}
Thanks in advance.
replace getActivity with getContext when you work in fragment,
You can read more here
What is different between getContext and getActivity from Fragment in support library?
Your activity should implement ExampleAdapter.OnItemClickListener
I'm having problems with showing JSONArray data on the Fragment. I am verified my links, Strings etc. But on the Debug console my request showing correct. I am suspecting JSONArray request but i can't find any errors.
Please, help!
D/Request::: 010-8470-0486
010-8472-0964
010-8474-2372
D/Request::: 010-8475-0089
D/Request::: 010-8475-7585
010-8478-0007
D/Request::: 010-8478-0573
010-8479-0311
010-8479-9234
D/Request::: 010-8481-2030
This is my Fragment
public class FragmentDB extends Fragment {
private View v;
private RecyclerView recyclerView;
private String url = "http://www.example.com/api.php";
private List<ModelDB> modelDBList;
public FragmentDB() {
}
#SuppressWarnings("UnnecessaryLocalVariable")
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (Objects.requireNonNull(getActivity()).checkSelfPermission(Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED &&
getActivity().checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED &&
getActivity().checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED)
return v;
} else {
Intent i10 = new Intent(getActivity(), PermissionActivity.class);
startActivity(i10);
Objects.requireNonNull(getActivity()).finish();
}
v = inflater.inflate(R.layout.frag_db, container, false);
recyclerView = v.findViewById(R.id.rv_db);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
RecyclerView.LayoutManager layoutManager = linearLayoutManager;
recyclerView.setLayoutManager(layoutManager);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), linearLayoutManager.getOrientation());
modelDBList = new ArrayList<>();
DbRvAdapter adapter = new DbRvAdapter(getContext(), modelDBList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
recyclerView.addItemDecoration(dividerItemDecoration);
recyclerView.setHasFixedSize(true);
Objects.requireNonNull(getActivity()).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
getDBLogs();
return v;
}
#SuppressWarnings({"LogNotTimber", "deprecation"})
private void getDBLogs() {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// Do something with the response
try {
for ( int i = 0; i < response.length(); i++) {
JSONObject obj = response.getJSONObject(i);
ModelDB dblist = new ModelDB();
dblist.setPhone_number(obj.getString("phone_number"));
dblist.setInfo1(obj.getString("info1"));
modelDBList.add(dblist);
Log.d("Request:: ", obj.getString("phone_number"));
}
} catch(JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
Log.e("Volley", error.toString());
}
});
RequestQueue rq = Volley.newRequestQueue(Objects.requireNonNull(getActivity()).getApplicationContext());
rq.add(jsonArrayRequest);
}
}
and ModelDB class
public class ModelDB {
public String phone_number;
public String info1;
public ModelDB() {
}
public ModelDB(String phone_number, String info1) {
this.phone_number = phone_number;
this.info1 = info1;
}
public String getPhone_number() {
return phone_number;
}
public void setPhone_number(String phone_number) {
this.phone_number = phone_number;
}
public String getInfo1() {
return info1;
}
public void setInfo1(String info1) {
this.info1 = info1;
}
}
and adapter class
public class DbRvAdapter extends RecyclerView.Adapter<DbRvAdapter.ViewHolder> {
public static final String KEY_DBPHONENUMBER = "phone_number";
public static final String KEY_DBINFO = "info1";
private Context context;
private List<ModelDB> list;
public DbRvAdapter(Context context, List<ModelDB> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_db, parent, false);
return new ViewHolder(v);
}
#SuppressWarnings("RecyclerView")
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
final ModelDB modelDB = list.get(position);
holder.textDBP.setText(modelDB.getPhone_number());
holder.textInfo1.setText(String.valueOf(modelDB.getInfo1()));
holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ModelDB modelDB1 = list.get(position);
Intent skipIntent = new Intent(v.getContext(), NumberActivity.class);
skipIntent.putExtra(KEY_DBINFO, modelDB1.getInfo1());
skipIntent.putExtra(KEY_DBPHONENUMBER, modelDB1.getPhone_number());
v.getContext().startActivity(skipIntent);
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textDBP, textInfo1;
public RelativeLayout relativeLayout;
public ViewHolder(View itemView) {
super(itemView);
textDBP = itemView.findViewById(R.id.tv_number);
textInfo1 = itemView.findViewById(R.id.tv_dbinfo);
}
}
}
Sorry for my bad English.
notify you adapter after the for loop body and declare the adapter globally
for ( int i = 0; i < response.length(); i++) {
............
modelDBList.add(dblist);
}
if(dblist != null and dblist.size() > 0){
adapter.notifyDataSetChanged();
}
It looks like you didn't update list of modelDB's inside adapter after the parsing of a network call result.
I am new to android, developing an android application but I stuck here. RecyclerView shows empty. There are no errors or crashes in the log. I deleted and created new but same issue. I cant find what's wrong.
java code for main activity
public class HomeActivity extends AppCompatActivity {
private RecyclerView rcview1;
private RecyclerView.Adapter cmpadapter1;
private List<commdtylist> listitems2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
rcview1 = (RecyclerView) findViewById(R.id.commoditylist);
rcview1.setItemAnimator(new DefaultItemAnimator());
listitems2 = new ArrayList<>();
rcview1.setHasFixedSize(true);
viewcmp();
}
public void viewcmp() {
StringRequest stringRequest=new StringRequest(Request.Method.POST, otpur, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jobj = new JSONObject(response);
JSONArray jsonArray = jobj.getJSONArray("Details");
for (int i = 0; i < jsonArray.length(); i++) {
jobj = jsonArray.getJSONObject(i);
commdtylist item = new commdtylist(
jobj.getString("quantity_entitle"),
jobj.getString("comm_code"),
jobj.getString("item_description")
);
listitems2.add(item);
}
cmpadapter1 = new CommdityviewAdapter(listitems2, getApplicationContext());
rcview1.setAdapter(cmpadapter1);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> param = new HashMap<>();
param.put("rc_no", crd);
return param;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
commdtylist
public class commdtylist {
private String quantity_entitle;
private String comm_code;
private String item_description;
public commdtylist(String quantity_entitle, String comm_code, String item_description) {
this.quantity_entitle = quantity_entitle;
this.comm_code = comm_code;
this.item_description = item_description;
}
public String getquantity_entitle() {
return quantity_entitle;
}
public String getcomm_code() {
return comm_code;
}
public String getitem_description() {
return item_description;
}
}
Adapter
public class CommdityviewAdapter extends RecyclerView.Adapter<CommdityviewAdapter.RViewHolder> {
private List<commdtylist> listitems2;
private Context context;
int lastPosition = -1;
public CommdityviewAdapter(List<commdtylist> listitems2, Context context) {
this.listitems2 = listitems2;
this.context = context;
}
public static Toast t = null;
#Override
public RViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.view_cmdstyle,parent,false);
return new RViewHolder(v);
}
#Override
public void onBindViewHolder(final RViewHolder holder,final int position) {
final commdtylist listitem=listitems2.get(position);
holder.quantity_entitle.setText(listitem.getquantity_entitle());
holder.comm_code.setText(listitem.getcomm_code());
holder.item_description.setText(listitem.getitem_description());
setAnimation(holder.itemView, position);
}
private void setAnimation(View itemView, int position) {
// If the bound view wasn't previously displayed on screen, it's animated
if (position > lastPosition)
{
Animation animation = AnimationUtils.loadAnimation(itemView.getContext(), R.anim.up_from_bottom);
itemView.startAnimation(animation);
lastPosition = position;
}
else{
Animation animation = AnimationUtils.loadAnimation(itemView.getContext(), R.anim.down_from_top);
//android.R.anim.slide_in_left
itemView.startAnimation(animation);
lastPosition = position;
}
}
#Override
public int getItemCount() {
return listitems2.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public class RViewHolder extends RecyclerView.ViewHolder{
public TextView quantity_entitle,comm_code,item_description;
public RViewHolder(View itemView) {
super(itemView);
quantity_entitle=(TextView)itemView.findViewById(R.id.quantity_entitle);
comm_code=(TextView)itemView.findViewById(R.id.comm_code);
item_description=(TextView)itemView.findViewById(R.id.item_description);
}
}
}
You have to add LayoutManager to RecyclerView . Use setLayoutManager (RecyclerView.LayoutManager layout) method to set LayoutManager to RecyclerView. If you don't set any LayoutManager you will not see any data.
LinearLayoutManager manager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(manager);
final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerview.setLayoutManager(layoutManager);
Hope to help you.
Please set RecyclerView's layoutmanager with setLayoutManager method.
Set the layout manager to the recylerView
rcview1.setAdapter(cmpadapter1);
rcview1.setLayoutManager(new LinearLayoutManager(this));
make some change in home activity like
private CommdityviewAdapter cmpadapter1; // replace private RecyclerView.Adapter cmpadapter1;
rcview1.setLayoutManager(new LinearLayoutManager(this));
and when you set the adapter in recyclerview then after notifiy to adapter.
cmpadapter1.notifyDataSetChanged();