I need a help. I am developing dynamic tabs with dynamic data in viewpager fragment's list. Somehow i got the dynamic tabs and hit API in placeholder fragment to get the recyclerview list.
there are two issue. 1. design is overlapping the tabs and 2. its loading 3rd id data first.
here is the code.
here is main class
public class NewsFeed extends Fragment {
private static RecyclerView listView;
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
private TabLayout tabLayout;
private ViewPager viewPager;
private RecyclerView recyclerView;
private ApiInterface apiInterface;
private List<BlogCatData> list = new ArrayList<BlogCatData>();
private BlogCatListAdaptor adapter;
private String item;
private ArrayList<BlogCatData> dataModelList = new ArrayList<BlogCatData>();
private ArrayList<String> CatTitleList = new ArrayList<>();
private static ArrayList<String> CatIdList = new ArrayList<>();
private View view1;
private View v;
// private ArrayAdapter<BlogCatData> adapter;
public NewsFeed() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_news_feed, container, false);
getAllBlogCat();
return v;
}
private void setViewIDs() {
tabLayout = v.findViewById(R.id.tabs);
viewPager = v.findViewById(R.id.container);
setUpViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
}
private void getAllBlogCat() {
// avi.show();
apiInterface = APIClient.getClient().create(ApiInterface.class);
Call<BlogCatModel> call = apiInterface.GETBlogCategory();
call.enqueue(new Callback<BlogCatModel>() {
#Override
public void onResponse(Call<BlogCatModel> call, retrofit2.Response<BlogCatModel> response) {
if (response.isSuccessful()) {
CatIdList.clear();
list = response.body().getDATA();
for (int i = 0; i < list.size(); i++) {
CatTitleList.add(list.get(i).getTITLE());
CatIdList.add(list.get(i).getID());
}
Log.v("CatTitle", CatTitleList.toString());
Log.v("CatId", CatIdList.toString());
setViewIDs();
// adapter.setPostList(list)
} else {
try {
JSONObject jObjError = new JSONObject(response.errorBody().string());
Toast.makeText(getApplicationContext(), jObjError.getString("message"), Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onFailure(Call<BlogCatModel> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.toString(), Toast.LENGTH_SHORT).show();
call.cancel();
}
});
}
private void setUpViewPager(ViewPager viewPager) {
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
for (int i = 0; i < CatTitleList.size(); i++) {
Bundle bundle = new Bundle();
bundle.putString("id", CatIdList.get(i));
PlaceholderFragment categoryList = new PlaceholderFragment();
categoryList.setArguments(bundle);
sectionsPagerAdapter.addFragment(categoryList, CatTitleList.get(i));
}
sectionsPagerAdapter.notifyDataSetChanged();
viewPager.setAdapter(sectionsPagerAdapter);
}
public static class PlaceholderFragment extends Fragment {
private final static String TAG = PlaceholderFragment.class.getSimpleName();
private static String item;
private static ArrayList<String> dataModelList = new ArrayList<String>();
// private ArrayAdapter<Model> adapter;
private RecyclerView listView;
private List<BlogData> dataList = new ArrayList<>();
private BlogListAdaptor blogListAdaptor;
private static String id;
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
id = CatIdList.get(sectionNumber);
Bundle args = new Bundle();
args.putString("ID", id);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment__newsfeed_placeholder, container, false);
listView = view.findViewById(R.id.recycler_view);
getBlog(Id);
setBlog();
return view;
}
private void getBlog(String id) {
ApiInterface apiInterface = APIClient.getClient().create(ApiInterface.class);
Call<BlogModel> call = apiInterface.getNewsByCategory(id);
call.enqueue(new Callback<BlogModel>() {
#Override
public void onResponse(Call<BlogModel> call, retrofit2.Response<BlogModel> response) {
if (response.isSuccessful()) {
dataList = response.body().getDATA();
blogListAdaptor.setPostList(dataList);
} else {
try {
JSONObject jObjError = new JSONObject(response.errorBody().string());
Toast.makeText(getApplicationContext(), jObjError.getString("message"), Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onFailure(Call<BlogModel> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.toString(), Toast.LENGTH_SHORT).show();
call.cancel();
}
});
}
private void setBlog() {
blogListAdaptor = new BlogListAdaptor(getActivity(), dataList);
listView.setAdapter(blogListAdaptor);
listView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
listView.setLayoutManager(linearLayoutManager);
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 0);
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public int getCount() {
return mFragmentTitleList.size();
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
}
return mFragmentTitleList.get(position);
}
#Override
public int getItemPosition(Object object) {
return super.getItemPosition(object);
}
}
}
and here is the adapter class for recyclerview
public class BlogListAdaptor extends RecyclerView.Adapter<BlogListAdaptor.MyViewHlder> {
private Activity activity;
private List<BlogData> list;
private boolean valid;
private EditText name, email, phone, date, noOfGuest, msg;
private Spinner partyMode, timeSlot;
private AlertDialog alertDialog;
final Calendar myCalendar = Calendar.getInstance();
private String PartyModeStr, TimeSlotStr;
private String Id;
private String title;
public BlogListAdaptor(Activity activity, List<BlogData> list) {
this.activity = activity;
this.list = list;
}
public void setPostList(List<BlogData> dataList) {
list = dataList;
notifyDataSetChanged();
}
#NonNull
#Override
public MyViewHlder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.blog_list_layout, viewGroup, false);
MyViewHlder my = new MyViewHlder(view);
return my;
}
#Override
public void onBindViewHolder(#NonNull MyViewHlder myViewHlder, int i) {
myViewHlder.Title.setText(list.get(i).getTITLE());
myViewHlder.Author.setText(list.get(i).getAUTHOR());
if (list.get(i).getIMGSRC() != null)
Glide.with(activity).load(Constant.ImgRoot + list.get(i).getIMGSRC())
.into(myViewHlder.Image);
myViewHlder.cardview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(activity, DetailActivity.class);
intent.putExtra("Id", list.get(i).getID());
intent.putExtra("Title", list.get(i).getTITLE());
intent.putExtra("Author", list.get(i).getAUTHOR());
intent.putExtra("Content", list.get(i).getCONTENT());
activity.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return list.size();
}
class MyViewHlder extends RecyclerView.ViewHolder {
private TextView Title, Author;
private ImageView Image;
private CardView cardview;
public MyViewHlder(#NonNull View itemView) {
super(itemView);
Image = itemView.findViewById(R.id.image);
Title = itemView.findViewById(R.id.title);
Author = itemView.findViewById(R.id.author);
cardview = itemView.findViewById(R.id.cardview);
}
}
}
Please help me out, to call api...
fragment_newsfeed_placeholder
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
fragment_news_feed
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
app:tabGravity="center"
app:tabMode="scrollable"
app:tabTextColor="#ffffff" />
<androidx.viewpager.widget.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/tabs" />
Related
I have a RecyclerView, it has items in it. I need each item to have its own Activity, that is, we have item1 by clicking on it, Activity1 opens, there is also item2 about clicking on it, Activity2 is opened. Can this be done somehow? If so, how? I managed to make it so that when I clicked, the same Fragment opened, and the text changes depending on which item was clicked. But it doesn't quite suit me.
Fragment where the RecyclerView is located
public class FragmentAttractionRecyclerView extends Fragment {
private RecyclerView mRec;
private AttractionsAdapter adapter;
private ArrayList<AttractionsItem> exampleList;
private RecyclerView.LayoutManager mLayoutManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_attraction_test_2, container, false);
}
#SuppressLint("InflateParams")
#Override
public void onViewCreated(#NonNull final View view, #Nullable Bundle savedInstanceState) {
createExampleList();
buildRecyclerView();
}
public void createExampleList() {
exampleList = new ArrayList<>();
exampleList.add(new AttractionsItem(R.mipmap.unnamed, R.drawable.ic_kid, "Baby островок", "Детский", "60₽","Максимальное кол-во детей","10","Возраст","С 1-го до 6 лет"));
exampleList.add(new AttractionsItem(R.mipmap.unnamed, R.drawable.ic_kid, "Виражи", "Детский", "80₽","Максимальное кол-во пассажиров","24", "Возраст","От 4-х до 12 лет"));
exampleList.add(new AttractionsItem(R.mipmap.unnamed, R.drawable.ic_kid, "Вокруг света", "Детский", "50₽","Максимальное кол-во пассажиров","12","Возраст","От 3-х до 12 лет"));
exampleList.add(new AttractionsItem(R.mipmap.unnamed, R.drawable.ic_interactive, "5D кинотеатр", "Интерактивный", "120₽","Максимальное кол-во пассажиров","","Возраст","С 6 лет"));
}
public void buildRecyclerView() {
mRec = requireView().findViewById(R.id.attraction_recycler);
adapter = new AttractionsAdapter(exampleList);
mLayoutManager = new LinearLayoutManager(getContext());
mRec.setLayoutManager(mLayoutManager);
mRec.setAdapter(adapter);
}
}
Adapter for RecyclerView
public class AttractionsAdapter extends RecyclerView.Adapter<AttractionsAdapter.AttractionsViewHolder> {
public ArrayList<AttractionsItem> mFavList;
public AttractionsAdapter(ArrayList<AttractionsItem> favList) {
mFavList = favList;
}
#NonNull
#Override
public AttractionsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_attraction, parent, false);
AttractionsViewHolder evh = new AttractionsViewHolder(v);
return evh;
}
public static class AttractionsViewHolder extends RecyclerView.ViewHolder {
public ImageView card_image_1, card_image_2;
public TextView card_text_1, card_text_2, card_text_3,attraction_menu_1_1,attraction_menu_1_2;
public CardView Card;
public AttractionsViewHolder(View itemView) {
super(itemView);
card_image_1 = itemView.findViewById(R.id.card_image_1);
card_image_2 = itemView.findViewById(R.id.card_image_2);
card_text_1 = itemView.findViewById(R.id.card_text_1);
card_text_2 = itemView.findViewById(R.id.card_text_2);
card_text_3 = itemView.findViewById(R.id.card_text_3);
attraction_menu_1_1 = itemView.findViewById(R.id.attraction_menu_1_1);
attraction_menu_1_2 = itemView.findViewById(R.id.attraction_menu_1_2);
Card = itemView.findViewById(R.id.Card);
}
}
#Override
public void onBindViewHolder(AttractionsViewHolder holder, int position) {
AttractionsItem currentItem = mFavList.get(position);
holder.card_image_1.setImageResource(currentItem.getImg1());
holder.card_image_2.setImageResource(currentItem.getImg2());
holder.card_text_1.setText(currentItem.get_attraction_name());
holder.card_text_2.setText(currentItem.get_attraction_type());
holder.card_text_3.setText(currentItem.get_attraction_cost());
holder.Card.setOnClickListener(v -> {
FragmentBlancAttraction fragment = new FragmentBlancAttraction(); // you fragment
FragmentManager fragmentManager = ((FragmentActivity) v.getContext()).getSupportFragmentManager(); // instantiate your view context
Bundle bundle = new Bundle();
bundle.putString("name", currentItem.get_attraction_name());
bundle.putString("menu_1_1", currentItem.get_attraction_menu_1_1());
bundle.putString("menu_1_2", currentItem.get_attraction_menu_1_2());
bundle.putString("menu_2_1", currentItem.get_attraction_menu_2_1());
bundle.putString("menu_2_2", currentItem.get_attraction_menu_2_2());
fragment.setArguments(bundle);
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.animator.nav_default_enter_anim, R.animator.nav_default_exit_anim,
R.animator.nav_default_pop_enter_anim, R.animator.nav_default_pop_exit_anim);
fragmentTransaction.replace(R.id.fragment, fragment);// your container and your fragment
fragmentTransaction.addToBackStack("tag");
fragmentTransaction.commit();
});
}
#Override
public int getItemCount() {
return mFavList.size();
}
}
public class AttractionsItem
{
private int mImg_1,mImg_2;
private final String mText_attraction_name;
private final String mText_attraction_type;
private final String mText_attraction_cost;
private final String mText_attraction_menu_1_1;
private final String mText_attraction_menu_1_2;
private final String mText_attraction_menu_2_1;
private final String mText_attraction_menu_2_2;
public AttractionsItem(int img1,int img2, String text_attraction_name, String text_attraction_type, String text_attraction_cost, String text_attraction_menu_1_1, String text_attraction_menu_1_2, String text_attraction_menu_2_1, String text_attraction_menu_2_2)
{
mImg_1 = img1;
mImg_2 = img2;
mText_attraction_name = text_attraction_name;
mText_attraction_type = text_attraction_type;
mText_attraction_cost = text_attraction_cost;
mText_attraction_menu_1_1 = text_attraction_menu_1_1;
mText_attraction_menu_1_2 = text_attraction_menu_1_2;
mText_attraction_menu_2_1 = text_attraction_menu_2_1;
mText_attraction_menu_2_2 = text_attraction_menu_2_2;
}
public int getImg1()
{
return mImg_1;
}
public int getImg2()
{
return mImg_2;
}
public String get_attraction_name()
{
return mText_attraction_name;
}
public String get_attraction_type()
{
return mText_attraction_type;
}
public String get_attraction_cost()
{
return mText_attraction_cost;
}
public String get_attraction_menu_1_1()
{
return mText_attraction_menu_1_1;
}
public String get_attraction_menu_1_2()
{
return mText_attraction_menu_1_2;
}
public String get_attraction_menu_2_1()
{
return mText_attraction_menu_2_1;
}
public String get_attraction_menu_2_2()
{
return mText_attraction_menu_2_2;
}
}
The positon param inside onBindViewHolder() method tells you which item of your RecyclerView clicked.
Use this to control your program and in out of onBindViewHolder() method you can get your item position by getAdapterPosition().
holder.Card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (position) {
case 0: {
// Start first activity.
break;
}
case 1: {
// Start Second activity.
break;
}
}
}
});
I am trying to pass data Adapter class to TabView Layout. I have used fragment in tab. I want to pass data from adapter to fragment (fragment class for tab).
________________________________________Adapter Class________________________________________________
package com.livediscount.restaurants.Adapter;
public class LiveContestAdapter extends RecyclerView.Adapter<LiveContestAdapter.MyViewHolder> {
Context context;
List<Contest_Data> contest_data;
public LiveContestAdapter(Context context, List<Contest_Data> contest_data) {
this.context=context;
this.contest_data=contest_data;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
context=viewGroup.getContext();
View vh= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.custom_list_win_iphone,viewGroup,false);
MyViewHolder myViewHolder=new MyViewHolder(vh);
return myViewHolder;
}
#Override
public void onBindViewHolder(#NonNull final LiveContestAdapter.MyViewHolder myViewHolder, final int i) {
final Contest_Data contest_position = contest_data.get(i);
Picasso.with(context).load(contest_data.get(i).getContestImage()).error(R.drawable.damme).placeholder(R.drawable.damme).into(myViewHolder.img);
myViewHolder.remainSlot.setText(contest_data.get(i).getContestTotal_slot());
myViewHolder.ent_fee.setText(contest_data.get(i).getContestEntry_Fee());
myViewHolder.Booked_Slot.setText(contest_data.get(i).getContestBooked());
final String contest_status = contest_data.get(i).getContestStatus();
String previous_contest = contest_data.get(i).getPrevious_contest();
String winner_announce = contest_data.get(i).getWinner_announce();
}
#Override
public int getItemCount() {
return contest_data.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView name;
ImageView img;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
//name=itemView.findViewById(R.id.totalslot);
img=itemView.findViewById(R.id.imageView2);
htp = itemView.findViewById(R.id.button2);
remainSlot=itemView.findViewById(R.id.tvTotalSlotNumber);
}
}
}
___________________________________________AppCompactActivity______________________________________
public class PrizeBreakup extends AppCompatActivity {
ImageButton back;
TabLayout tabLayout;
ViewPager viewPager;
String contest_id,contest_name;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prize_breakup);
back = findViewById(R.id.back_button);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
tabLayout= findViewById(R.id.tabs);
viewPager = findViewById(R.id.container);
PrizeLayoutAdapter adapter = new PrizeLayoutAdapter(getSupportFragmentManager());
adapter.add(new PrizeLayout(),"Prize Breakup");
adapter.add(new WinnerLayout(),"Winners");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
//here
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("contestid1", "contest_id");
editor.apply();
/* Bundle bundle = getIntent().getExtras();
assert bundle!= null;
contest_id = bundle.getString("contest_id");
contest_name = bundle.getString("contest_name");*/
/* Bundle data = new Bundle();
data.putString("contestid1","contest_id");
Fragment argumentFragment = new PrizeLayout();
argumentFragment.setArguments(data);*/
}
}
_____________________________________PrizeLayout Fragment________________________________________
package com.livediscount.restaurants;
public class PrizeLayout extends Fragment {
List<Contest_Data> contest_data;
LiveContestAdapter live_contest_adapter;
private RecyclerView recyclerView;
TextView ContestId;
public static PrizeLayout newInstance() {
return new PrizeLayout();
}
#Override
public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.prize_layout, container, false);
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String contestid = getActivity().prefs.getString("contestid1", "contestid not found");
String Contest_id = this.getArguments().getString("edttext");
ContestId= view.findViewById(R.id.referral_code);
ContestId.setText(contestid);
return view;
}
}
________________________________________Winner Fragment______________________________________________
package com.livediscount.restaurants;
public class WinnerLayout extends Fragment {
private List<Winner_data> winner_data=new ArrayList<>();
private RecyclerView recyclerView_winner;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container , Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.winner_layout,container,false);
recyclerView_winner = view.findViewById(R.id.Recyclerview_Winner);
if(winner_data!=null)
{
winner_data.clear();
}
Winner_Data();
return view;
}
private void Winner_Data() {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
String url = ("http://livediscounts.in/webservices/User_interface/Winner_List?contest_id=\"+razorpayPaymentID+\"");
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//progressBar_contest.setVisibility(View.GONE);
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("status").equals("1")) {
JSONArray jsonArray = jsonObject.getJSONArray("records");
/*for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
Winner_data wd = new Winner_data();
cd.setContestId(obj.getString("id"));
cd.setContestName(obj.getString("name"));
cd.setContestImage(obj.getString("prize_1"));
cd.setContestDescription(obj.getString("description"));
cd.setContestType(obj.getString("type"));
cd.setContestEntry_Fee(obj.getString("entry_fee"));
cd.setContestTotal_slot(obj.getString("total_slot"));
cd.setContestTotal_winner(obj.getString("total_winner"));
cd.setContestPrice_Description(obj.getString("price_description"));
cd.setContestPrize_21(obj.getString("prize_21"));
cd.setContestPrize_22(obj.getString("prize_22"));
cd.setContestPrize_31(obj.getString("prize_31"));
cd.setContestPrize_32(obj.getString("prize_32"));
cd.setContestPrize_41(obj.getString("prize_41"));
cd.setContestPrize_42(obj.getString("prize_42"));
cd.setContestPrize_51(obj.getString("prize_51"));
cd.setContestPrize_52(obj.getString("prize_52"));
cd.setContestPrize_61(obj.getString("prize_61"));
cd.setContestPrize_62(obj.getString("prize_62"));
cd.setContestPrize_71(obj.getString("prize_71"));
cd.setContestPrize_72(obj.getString("prize_72"));
cd.setContestStatus(obj.getString("status"));
cd.setContestContest_Note(obj.getString("contest_note"));
cd.setContestStart_date(obj.getString("start_date"));
cd.setContestEnd_date(obj.getString("end_date"));
cd.setContestBooked(obj.getString("booked_slot"));
winner_data.add(wd);
}*/
/*WinnerAdapter winnerAdapter = new WinnerAdapter(getApplicationContext(), winner_data);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView_winner.setLayoutManager(llm);
recyclerView_winner.setAdapter(winnerAdapter);*/
} else {
// Toast.makeText(getApplicationContext(),"Something went Wrong",Toast.LENGTH_SHORT).show();
}
} catch (Exception ex) {
//progressBar_contest.setVisibility(View.GONE);
//Toast.makeText(getApplicationContext(),"No Data Found",Toast.LENGTH_LONG).show(); ex.printStackTrace();
}
}
}
,
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(getApplicationContext(),"No Internet Connection",Toast.LENGTH_LONG).show();
}
}
);
requestQueue.add(request);
}
}
you can use shared pref using parent activity.
The pager returns the 1st object in the array list, and keeps returning the 1st object even if i swing left and right, did a lot of debugging, and for some reason when the pager get's to getItem(int position) it start's going crazy, it FINDS the corresponding object , then looks a the previous object(pos-1) then does some other weird things and returns the 1st obj in arrayList.
This method is called within the ViewHolder of RecyclerViewAdapter
#Override
public void onClick(View v) {
Intent i = ProductPageActivity.newIntent(v.getContext(),mProduct.getId());
v.getContext().startActivity(i);
}
}
public class ProductFragment extends Fragment {
private static final String TAG = "ProductFragment";
private static final String ARGUMENT_PROD_ID = "prod_id";
private TextView mTitle,mDesc,mImgUrl,mPrice;
private List<Product> mProducts;
private Product product;
public static Fragment newInstance(UUID productID) {
Bundle args = new Bundle();
args.putSerializable(ARGUMENT_PROD_ID,productID);
ProductFragment frag = new ProductFragment();
frag.setArguments(args);
return frag;
}
public ProductFragment() {}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getArguments() != null) {
UUID id = (UUID) getArguments().getSerializable(ARGUMENT_PROD_ID);
product = ProductHolder.get(getContext()).getProduct(id);
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.product_fragment,container,false);
setWidgets(v);
setDataOnText();
return v;
}
private void setDataOnText(){
mTitle.setText(product.getTitle());
mDesc.setText(product.getDesc());
mPrice.setText(product.getPrice());
}
private void setWidgets(View v) {
mTitle = (TextView) v.findViewById(R.id.title);
mDesc = (TextView) v.findViewById(R.id.desc);
mPrice = (TextView) v.findViewById(R.id.price);
}
}
public class ProductPageActivity extends AppCompatActivity {
private static final String PRODUCT_ID = "com.example.cmd.testproject.Activitys.ProductPageActivity.product_id";
private UUID productId;
private ViewPager mPager;
private List<Product> mProducts;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product_page_activity);
productId = (UUID) getIntent().getSerializableExtra(PRODUCT_ID);
mPager = (ViewPager) findViewById(R.id.viewPager);
mProducts = ProductHolder.get(this).getProducts();
FragmentManager fragmentManager = getSupportFragmentManager();
mPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) {
#Override
public Fragment getItem(int position) {
Product pr = mProducts.get(position);
return ProductFragment.newInstance(pr.getId());
}
#Override
public int getCount() {
return mProducts.size();
}
});
for (int i = 0; i < mProducts.size(); i++) {
if (mProducts.get(i).getId().equals(productId)) {
mPager.setCurrentItem(i);
break;
}
}
}
public static Intent newIntent(Context packageContext, UUID productID) {
Intent intent = new Intent(packageContext, ProductPageActivity.class);
intent.putExtra(PRODUCT_ID, productID);
return intent;
}
}
public class ProductHolder {
private static final String TAG = "ProductHolder";
private static ProductHolder sProductHolder;
private List<Product> mProducts;
public static ProductHolder get(Context ctx) {
if(sProductHolder == null) {
sProductHolder = new ProductHolder(ctx);
}
return sProductHolder;
}
private ProductHolder(Context ctx) {
mProducts = new ArrayList<>();
for (int i = 0; i < 4; i++) {
Product product = new Product("Product = " + i, "Desc = "
+ i, "ImgUrl = " + i, "Price = " + i + 2.2);
mProducts.add(product);
}
}
public Product getProduct(UUID prodId) {
for (Product pr:mProducts) {
if(pr.getId().equals(prodId));
return pr;
}
return null;
}
public List<Product> getProducts() {
return mProducts;
}
}
ArrayList.size() showing zero every time. Actually im trying to Filter the Data using the data stored on the ArrayList
This is my HomeFragment.Java
public class HomeFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private static final String TAG_check="check";
public RecyclerView recyclerView;
SearchView realsv;
private AlbumsAdapter adapter;
private ArrayList<Album> albumList;
private ArrayList<Album> test;
private Album album;
public ImageView imga;
public CollapsingToolbarLayout collapsingToolbar;
public AppBarLayout appBarLayout;
ProgressDialog pd;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
realsv=(SearchView)rootView.findViewById(R.id.realsv);
recyclerView = (RecyclerView) rootView.findViewById(R.id.rcv);
//test.addAll(albumList);
//test.clear();
realsv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
Log.i("YES","FIRST STEP"+albumList.size());
newText=newText.toLowerCase();
for(Album al: albumList)
{
String title = al.getName().toLowerCase();
ArrayList<Album> test = new ArrayList<>();
Log.i("CHEK",title);
if(title.contains(newText)){
Log.i("CHEK ok",title+"ok");
test.add(al);
}
}
adapter.setFilter(test);
// adapter.getFilter().filter(newText);
return true;
}
});
initViews();
return rootView;
}
private void initViews(){
pd = new ProgressDialog(getActivity());
pd.setMessage("Fetching Data...");
pd.setCancelable(false);
pd.show();
albumList = new ArrayList<>();
adapter = new AlbumsAdapter(getActivity(), albumList);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
loadJSON();
}
private void loadJSON(){
try{
Client Client = new Client();
//this is where it all changes
Hindi apiService = Client.getClient().create(Hindi.class);
Call<AlbumsResponse> call = apiService.getAlbums();
call.enqueue(new Callback<AlbumsResponse>() {
#Override
public void onResponse(Call<AlbumsResponse> call, Response<AlbumsResponse> response) {
ArrayList<Album> items = response.body().getAlbums();
recyclerView.setAdapter(new AlbumsAdapter(getActivity(), items));
recyclerView.smoothScrollToPosition(0);
pd.hide();
}
#Override
public void onFailure(Call<AlbumsResponse> call, Throwable t) {
Log.d("Error", t.getMessage());
// Toast.makeText(MainActivity.this, "Error Fetching Data!", Toast.LENGTH_SHORT).show();
pd.hide();
}
});
}catch (Exception e){
Log.d("Error", e.getMessage());
// Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
This is My adapter Class for Recyclerview
public class AlbumsAdapter extends RecyclerView.Adapter<AlbumsAdapter.MyViewHolder>{
private Context mContext;
private ArrayList<Album> albumList;
//private List<Album> newList;
public AlbumsAdapter(Context mContext, ArrayList<Album> albuList) {
this.mContext = mContext;
this.albumList = albuList;
// this.newList=albuList;
}
#Override
public AlbumsAdapter.MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.album_card, viewGroup, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final AlbumsAdapter.MyViewHolder viewHolder, int i) {
viewHolder.title.setText(albumList.get(i).getName());
viewHolder.count.setText(albumList.get(i).getLang());
//load album cover using picasso
Picasso.with(mContext)
.load(albumList.get(i).getThumbnail())
.placeholder(R.drawable.load)
.into(viewHolder.thumbnail);
}
/**
* Showing popup menu when tapping on 3 dots
*/
private void showPopupMenu(View view) {
// inflate menu
PopupMenu popup = new PopupMenu(mContext, view);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu_album, popup.getMenu());
popup.setOnMenuItemClickListener(new MyMenuItemClickListener());
popup.show();
}
public void setFilter(ArrayList<Album> nn){
albumList= new ArrayList<Album>();
for (Album al:nn){
albumList.add(al);
}
notifyDataSetChanged();
}
/**
* Click listener for popup menu items
*/
class MyMenuItemClickListener implements PopupMenu.OnMenuItemClickListener {
public MyMenuItemClickListener() {
}
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_add_favourite:
Toast.makeText(mContext, "Add to favourite", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_play_next:
Toast.makeText(mContext, "Play next", Toast.LENGTH_SHORT).show();
return true;
default:
}
return false;
}
}
#Override
public int getItemCount() {
return albumList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, count;
public ImageView thumbnail, overflow;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
count = (TextView) view.findViewById(R.id.count);
thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
// overflow = (ImageView) view.findViewById(R.id.overflow);
//on item click
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
int pos = getAdapterPosition();
if (pos != RecyclerView.NO_POSITION){
Album clickedDataItem = albumList.get(pos);
Intent intent = new Intent(mContext, Det.class);
intent.putExtra("name", albumList.get(pos).getName());
intent.putExtra("lang", albumList.get(pos).getLang());
intent.putExtra("thumbnail", albumList.get(pos).getThumbnail());
intent.putExtra("scrn",albumList.get(pos).getScrn());
intent.putExtra("ourl",albumList.get(pos).getOurl());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
// Toast.makeText(v.getContext(), "You clicked " + clickedDataItem.getName(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
`
This is Model Class Album.java
public class Album {
#SerializedName("name")
#Expose
private String name;
#SerializedName("lang")
#Expose
private String lang;
#SerializedName("thumbnail")
#Expose
private String thumbnail;
#SerializedName("scrn")
#Expose
private String scrn;
#SerializedName("ourl")
#Expose
private String ourl;
public Album() {
}
public Album(String name, String lang, String thumbnail, String scrn,
String ourl) {
this.name = name;
this.lang = lang;
this.thumbnail = thumbnail;
this.scrn=scrn;
this.ourl=ourl;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public String getScrn() {
return scrn;
}
public void setScrn(String scrn) {
this.scrn = scrn;
}
public String getOurl() {
return ourl;
}
public void setOurl(String ourl) {
this.ourl = ourl;
}
}
This is the AlbumResponse.java
public class AlbumsResponse {
#SerializedName("Album")
#Expose
private ArrayList<Album> albums;
public ArrayList<Album> getAlbums(){
return albums;
}
public void setAlbums(ArrayList<Album>albums){
this.albums = albums;
}
}
Ok so in your LoadJson method, you populate a new array called items and then populate your adapter with it. So in your adapter your albumList gets populated which is fine. But then in your OnQueryTextChanged method you check for your query string in albumList array, which you have declared in your Home fragment but never initialized. So hence no filter results. assign your items to albumlist and it will work
In your loadJson() method, in onResponse you are creating a new ArrayList to get all albums and not setting that to your global variable albumList.
So you should do this,
ArrayList<Album> items = response.body().getAlbums();
albumList.addAll(items);
I am trying to make a service call with Retrofit and RxJava. I am using Picasso 2.5.2 to upload image from the API call. I am getting the image displayed, but i am getting single image only. When I debug, I get size as 20 but the displayed is single. Any help on that would be great.
The Adapter class:
public class PopularMoviesAdapter extends RecyclerView.Adapter<PopularMoviesAdapter.MoviesViewHolder> {
private final String TAG = PopularMoviesAdapter.class.getSimpleName();
private Context context;
private List<MoviesResponse> movieItems = new ArrayList<>();
public PopularMoviesAdapter(Context context, List<MoviesResponse> movieItems) {
this.context = context;
this.movieItems = movieItems;
}
#Override
public MoviesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movies_grid_item, parent, false);
return new MoviesViewHolder(view);
}
#Override
public void onBindViewHolder(MoviesViewHolder holder, int position) {
List<Movies> movies = movieItems.get(position).getResults();
String imageUrl = IntentKeys.MOVIES_POSTER_ENDPOINT + movies.get(position).getPosterPath();
Log.d(TAG, "Poster URL from the API call: " + imageUrl);
Picasso.with(context).load(imageUrl).into(holder.imageView);
Glide.with(context).load(imageUrl).into(holder.imageView);
}
#Override
public int getItemCount() {
return movieItems.size();
}
class MoviesViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
public MoviesViewHolder(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.movies_grid_item_image);
}
}}
The fragment class:
public class PopularMoviesFragment extends Fragment {
private static final int COLUMN_COUNT = 2;
private List<MoviesResponse> responses;
private RecyclerView recyclerView;
private PopularMoviesAdapter popularMoviesAdapter;
private Subscription subscription;
private MoviesService service = RetrofitManager.getMoviesClient().create(MoviesService.class);
public PopularMoviesFragment() {
responses = new ArrayList<>();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_popular_movies, container, false);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(
getActivity(),
COLUMN_COUNT,
LinearLayoutManager.VERTICAL,
false);
recyclerView = (RecyclerView) view.findViewById(R.id.popular_movies_recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new GridSpacingItemDecoration(COLUMN_COUNT, dpToPx(10), true));
recyclerView.setItemAnimator(new DefaultItemAnimator());
return view;
}
private int dpToPx(int dp) {
Resources r = getResources();
return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onStart() {
super.onStart();
getMoviesSubscription();
}
private void getMoviesSubscription() {
subscription = service.getPopularMovies(IntentKeys.POPULAR_MOVIES_API_KEY)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
new Action1<MoviesResponse>() {
#Override
public void call(MoviesResponse movies) {
responses.add(movies);
}
}, new Action1<Throwable>() {
#Override
public void call(Throwable throwable) {
}
}, new Action0() {
#Override
public void call() {
displayPosters();
}
}
);
}
private void displayPosters() {
popularMoviesAdapter = new PopularMoviesAdapter(getContext(), responses);
recyclerView.setAdapter(popularMoviesAdapter);
recyclerView.invalidate();
}
#Override
public void onDestroyView() {
super.onDestroyView();
if (subscription != null && subscription.isUnsubscribed()) {
subscription.unsubscribe();
}
}
}
Finally the layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/movies_grid_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/movies_grid_item_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"/>
</LinearLayout>
POJO:
public class Movies implements Serializable {
private String posterPath;
private Boolean adult;
private String overview;
private String releaseDate;
private List<Integer> genreIds = new ArrayList<Integer>();
private Integer id;
private String originalTitle;
private String originalLanguage;
private String title;
private String backdropPath;
private Float popularity;
private Integer voteCount;
private Boolean video;
private Float voteAverage;
// getters and setters ommitted and constructor
}
public class MoviesResponse implements Serializable {
private Integer page;
private List<Movies> results = new ArrayList<Movies>();
private Integer totalResults;
private Integer totalPages;
// getters and setters ommitted and constructor
}
Thanks!
Try
Context context = holder.itemView.getContext();
in your onBindViewHolder, so that you don't pass context around.
Also try adding popularMoviesAdapter.notifyDataSetChanged() in your fragment. Do you mind uploading your POJO?
in your adapter
public PopularMoviesAdapter(List<Movie> movies) {
this.movies = movies;
}
in your fragment
.subscribe(
new Action1<MoviesResponse>() {
#Override
public void call(MoviesResponse movies) {
responses.add(movies.getResults());
popularMoviesAdapter.notifyDataSetChanged()
}
}
Change
#Override
public void onBindViewHolder(MoviesViewHolder holder, int position) {
List<Movies> movies = movieItems.get(position);
String imageUrl = IntentKeys.MOVIES_POSTER_ENDPOINT + movies.get(position).getPosterPath();
Log.d(TAG, "Poster URL from the API call: " + imageUrl);
Picasso.with(context).load(imageUrl).into(holder.imageView);
Glide.with(context).load(imageUrl).into(holder.imageView);
}
This is your code to set adapter
popularMoviesAdapter = new PopularMoviesAdapter(getContext(), responses); recyclerView.setAdapter(popularMoviesAdapter);
your ArrayList responses = new ArrayList() // this is your arraylist which you are providing to adapter
debug and check size of responses that how many records will return i think it has on one object
i think your array is somewhat like this
responses [{
0,{
}
}];
so passs
popularMoviesAdapter = new PopularMoviesAdapter(getContext(), responses.get(0).getResults
); recyclerView.setAdapter(popularMoviesAdapter);