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.
Related
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" />
I am using Glide to load images in my app. When app launches Home fragment loads in MainActivity in Home fragment I am fetching images in view pager.When I switch between the fragments and come back to Home fragment it takes sometime to load images in view pager why don't it loads images quickly as I am using Caching property provided by Glide.
What I have been doing so far is
Home.java
public class Home extends Fragment{
ViewPager bannerViewPager;
BannerAdapter adapter;
List<BannerModel> banners;
TabLayout tabLayout;
RequestQueue requestQueue;
StringRequest stringRequest;
private static final String URI = "https://www.example.com";
public Home() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
tabLayout = view.findViewById(R.id.tabLayout);
bannerViewPager = view.findViewById(R.id.bannerViewpager);
tabLayout.setupWithViewPager(bannerViewPager, true);
banners = new ArrayList<>();
loadViewPager();
return view;
}
public void loadViewPager() {
requestQueue = Volley.newRequestQueue(getActivity());
stringRequest = new StringRequest(Request.Method.GET,URI, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for(int i = 0;i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String loadImages = jsonObject.getString("Image");
BannerModel model = new BannerModel(loadImages);
banners.add(model);
}
adapter = new BannerAdapter(banners,getActivity());
bannerViewPager.setAdapter(adapter);
}catch(JSONException e){
e.printStackTrace();
}
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
TastyToast.makeText(getActivity(),"Error:"+error.getMessage(),TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
}
});
requestQueue.add(stringRequest);
}
}
GlideSingleton.java
public class GlideSingleton {
private static GlideSingleton obj;
public RequestOptions options;
private GlideSingleton(){
options = new RequestOptions();
options.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC);
}
public static synchronized GlideSingleton getInstance(){
if(obj == null){
obj = new GlideSingleton();
}
return obj;
}
}
BannerAdapter.java
public class BannerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
Context context;
private List<BannerModel> banners;
public BannerAdapter(List<BannerModel> banners,Context context){
this.banners = banners;
this.context = context;
}
#Override
public int getCount() {
return banners.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object o) {
return view == o;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
assert layoutInflater != null;
View view = layoutInflater.inflate(R.layout.bannerlayout, null);
ImageView offerImage = view.findViewById(R.id.offerImage);
BannerModel model = banners.get(position);
Glide.with(context).load(model.getBannerImage()).apply(GlideSingleton.getInstance().options).into(offerImage);
container.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((LinearLayout)object);
}
}
Someone please let me know how can I load the images quickly once they get downloaded by network in image view.
Any help will be appreciated.
THANKS
Create new class
class SingletonRequestOptions
{
private static SingletonRequestOptions obj;
public RequestOptions options;
private SingletonRequestOptions () {
options = new RequestOptions();
options.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC);
}
// Only one thread can execute this at a time
public static synchronized SingletonRequestOptions getInstance()
{
if (obj==null)
obj = new SingletonRequestOptions ();
return obj;
}
}
Update your line with this
Glide.with(context).load(model.getBannerImage()).apply(SingletonRequestOptions.getInstance().options).into(offerImage);
I have responsed JSONObject from API and i tried to send the response to the module using setter then to the Recyclerview adapter but its not working
This is my fragment
public class ListViewActivityFragment extends Fragment {
List<AppShowModule> appShowModule;
RecyclerView AppRecyclerView;
List<AppShowModule> GetDataAdapter1;
RecyclerView.LayoutManager AppRecyclerViewlayoutManager;
RecyclerView.Adapter AppRecyclerViewadapter;
String jsonUrl = "https://itunes.apple.com/jo/rss/topfreeapplications/limit=50/json";
TextView text;
Context context;
RequestQueue requestQueue;
public ListViewActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_list_view, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
appShowModule = new ArrayList<>();
AppRecyclerView = (RecyclerView) getView().findViewById( R.id.AppRecyclerView );
text = (TextView) getView().findViewById(R.id.textView2);
AppRecyclerView.setHasFixedSize( true );
GetDataAdapter1 = new ArrayList<>();
AppRecyclerView.setLayoutManager( AppRecyclerViewlayoutManager );
JsonAppShowData();}
public void JsonAppShowData() {
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest( jsonUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONObject("feed").getJSONArray( "entry" );
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json1 = jsonArray.getJSONObject( i ).getJSONObject("im:name");
AppShowModule appShowModule111 = new AppShowModule();
String name = response.getJSONObject("feed").getJSONArray("entry").getJSONObject(i).getJSONObject("im:name").getString("label").toString();
text.setText(name);
appShowModule111.setAppName((name));}
} catch (JSONException e) {
e.printStackTrace();
}}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e( "LOG", error.toString() );
}
} );
requestQueue = Volley.newRequestQueue( getContext() );
requestQueue.add(jsonObjectRequest);
AppRecyclerView.setLayoutManager(new LinearLayoutManager(context));
AppRecyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1,this);
AppRecyclerView.setAdapter(AppRecyclerViewadapter);
}
}
and this is my adapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
List<AppShowModule> getDataAdapter;
Context MContext;
public RecyclerViewAdapter(List<AppShowModule> getDataAdapter, ListViewActivityFragment context){
super();
this.getDataAdapter = getDataAdapter;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.appitem, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position)
{
final AppShowModule getDataAdapter1 = getDataAdapter.get(position);
holder.NameTextView.setText(getDataAdapter1.getAppName());
Picasso.with(context).load(getDataAdapter1.getAppImageUrl()).into(holder.imgPost);
}
#Override
public int getItemCount() {
return getDataAdapter.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView NameTextView;
public ImageView imgPost;
LinearLayout lnrLayout;
public ViewHolder(View itemView) {
super(itemView);
NameTextView = (TextView) itemView.findViewById(R.id.appName);
imgPost = (ImageView) itemView.findViewById(R.id.appImage);
lnrLayout = (LinearLayout)itemView.findViewById(R.id.lnrLayout);
}
}
}
and this is my module
public class AppShowModule
{
private String appName;
private String appImageUrl;
public String getAppName() {
return appName;}
public void setAppName(String appName) {
this.appName = appName;}
public String getAppImageUrl() {
return appImageUrl;}
public void setAppImageUrl(String appImageUrl) {
this.appImageUrl = appImageUrl;}
}
Yo are creating the AppShowModule appShowModule111 = new AppShowModule(); Object but you never populated your adaapter with that object. Your JsonObjectRequest onResponse() should look like this;
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONObject("feed").getJSONArray( "entry" );
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json1 = jsonArray.getJSONObject( i ).getJSONObject("im:name");
AppShowModule appShowModule111 = new AppShowModule();
String name = response.getJSONObject("feed").getJSONArray("entry").getJSONObject(i).getJSONObject("im:name").getString("label").toString();
text.setText(name);
appShowModule111.setAppName((name));
GetDataAdapter1.add(appShowModule111);
}
AppRecyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1,ListViewActivityFragment.this);
AppRecyclerView.setAdapter(AppRecyclerViewadapter);
} catch (JSONException e) {
e.printStackTrace();
}}
I've a recyclerview adapter with 3 textviews. I used a model class to set texts. Now I want to use the same adapter with different layout and in a different class which only have 1 textview. When I tried, I got NullPointerException (may be becuz the other 2 textviews are blank). Is there any way to use same adapter with different layout and in different class?
// second class - I used 1 textview
public class Customers extends AppCompatActivity{
private CShowProgress cShowProgress;
private RecyclerView mRecyclerView;
private TimeLineAdapter mTimeLineAdapter;
private List<TimeLineModel> mDataList = new ArrayList<>();
private static final String CUSTOMERS = "http://192.168.200.3/ubooktoday/android/showspacustomerlist";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.customers);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
cShowProgress = CShowProgress.getInstance();
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(getLinearLayoutManager());
mRecyclerView.setHasFixedSize(true);
showCustomers();
}
private void showCustomers() {
if(mDataList!=null )mDataList.clear();
cShowProgress.showProgress(Customers.this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, CUSTOMERS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
cShowProgress.hideProgress();
try {
JSONArray jsonArray = new JSONArray(response);
for(int i=0; i<jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
TimeLineModel model = new TimeLineModel();
model.setCustname(obj.getString("customername"));
mDataList.add(model);
mTimeLineAdapter = new TimeLineAdapter(getApplicationContext(), R.layout.item_row_customer, mDataList);
mRecyclerView.setAdapter(mTimeLineAdapter);
}
mTimeLineAdapter.notifyDataSetChanged();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("spaid", "145");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
private LinearLayoutManager getLinearLayoutManager() {
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
return linearLayoutManager;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
}
return true;
}
}
// first class - I used all 3 textviews
public class Walkin extends Fragment{
private RecyclerView mRecyclerView;
private TimeLineAdapter mTimeLineAdapter;
private List<TimeLineModel> mDataList = new ArrayList<>();
private static final String DASHBOARD = "My API";
#Nullable
#Override
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.walkin, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(getLinearLayoutManager());
mRecyclerView.setHasFixedSize(true);
showDashboard();
}
private void showDashboard() {
if(mDataList!=null )mDataList.clear();
cShowProgress.showProgress(getActivity());
StringRequest stringRequest = new StringRequest(Request.Method.POST, DASHBOARD,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("walkinlist");
for(int i=0; i<jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
TimeLineModel model = new TimeLineModel();
model.setCustname(obj.getString("customername"));
model.setTime(obj.getString("serviceDuration"));
model.setServname(obj.getString("service"));
mDataList.add(model);
mTimeLineAdapter = new TimeLineAdapter(getActivity(), R.layout.item_row_dashboard, mDataList);
mRecyclerView.setAdapter(mTimeLineAdapter);
}
mTimeLineAdapter.notifyDataSetChanged();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getActivity(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("spaid", "145");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private LinearLayoutManager getLinearLayoutManager() {
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
return linearLayoutManager;
}
}
// Adapter class
public class TimeLineAdapter extends RecyclerView.Adapter<TimeLineViewHolder> {
private List<TimeLineModel> mFeedList;
int resource;
private Context mContext;
public TimeLineAdapter(Context mContext, int resource, List<TimeLineModel> feedList) {
this.resource = resource;
this.mContext = mContext;
mFeedList = feedList;
}
#Override
public TimeLineViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = View.inflate(parent.getContext(), resource, null);
return new TimeLineViewHolder(view, viewType);
}
#Override
public void onBindViewHolder(TimeLineViewHolder holder, int position) {
TimeLineModel timeLineModel = mFeedList.get(position);
holder.servicename.setText(timeLineModel.getServname());
holder.custname.setText(timeLineModel.getCustname());
holder.time.setText(timeLineModel.getTime());
}
#Override
public int getItemCount() {
return (mFeedList!=null? mFeedList.size():0);
}
}
// ViewHolder class
public class TimeLineViewHolder extends RecyclerView.ViewHolder {
public TextView servicename, custname, time;
public TimeLineViewHolder(View itemView, int viewType) {
super(itemView);
servicename = (TextView) itemView.findViewById(R.id.tv_service);
custname = (TextView) itemView.findViewById(R.id.tv_cust);
time = (TextView) itemView.findViewById(R.id.tv_time);
}
}
You can use the getItemViewType().
Make your adapter(here TimeLineAdapter) extend RecyclerView.Adapter only.
You can change the Adapter's constructer to recieve ItemType and use it in the getItemViewType
Override the int getItemViewType (int position) method in your adapter.
In the onCreateViewHolder you can differentiate between which layout you want to inflate by using the viewType parameter.
In onBindViewHolder use instanceof to check which ViewHolder was created and call the related bind functions
A Sample Code-
// Adapter class
public class TimeLineAdapter extends RecyclerView.Adapter{
.....
int type;
public TimeLineAdapter(Context mContext, int resource, List<TimeLineModel> feedList,int layoutType) {
.....
.....
type=layoutType;
}
#Override
public int getItemViewType(int position) {
return type;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType==1){
View view = View.inflate(parent.getContext(), resource, null);
return new TimeLineViewHolder(view, viewType);
}else{
View view = View.inflate(parent.getContext(), resource, null);
return new TimeLineViewHolder2(view, viewType);
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if(holder instanceof TimeLineViewHolder){
TimeLineModel timeLineModel = mFeedList.get(position);
((TimeLineViewHolder) holder).servicename.setText(timeLineModel.getServname());
......
}
else if(holder instanceof TimeLineViewHolder2){
....
....
}
}
#Override
public int getItemCount() {
return (mFeedList!=null? mFeedList.size():0);
}
}
I have five tabs they are 1.home 2.menu 3.cart 4.account 5.more.Here cart tab consist of list view which is having the remove button in it,when i click on that remove button it must refresh the fragment itself so that it can load new data from the Json
MainActivity.class
public class MainActivity extends BaseActivity implements OnFragmentInteractionListener {
#Bind(R.id.tabpager)
ViewPager mViewpager;
#Bind(R.id.tab_layout)
TabLayout mTabs;
private TabAdapter pageAdapter;
String home,menu,cart,account,more;
#Override
protected int getLayoutResource() {
return R.layout.activity_main;
}
#Override
protected void initVariables(Bundle savedInstanceState) {
home= getString(R.string.home);
menu = getString(R.string.menu);
cart = getString(R.string.cart);
account = getString(R.string.account);
more = getString(R.string.more);
}
#Override
protected void initData(Bundle savedInstanceState) {
setupViewPager(mViewpager);
setupTabLayout(mTabs);
}
public void setupViewPager(ViewPager viewPager) {
pageAdapter = new TabAdapter(getApplicationContext(), getSupportFragmentManager());
pageAdapter.addFragment(MainFragment.getInstance(home), home, R.drawable.home);
pageAdapter.addFragment(MenuItems.getInstance(menu), menu, R.drawable.menu);
pageAdapter.addFragment(Cart.getInstance(cart), cart, R.drawable.cart);
pageAdapter.addFragment(Account.getInstance(account), account, R.drawable.account);
pageAdapter.addFragment(More.getInstance(more), more, R.drawable.more);
viewPager.setAdapter(pageAdapter);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Session cartsession=new Session(getApplicationContext());
if (cartsession.isLoggedIn()){
if (position==2){
((Cart) pageAdapter.getItem(position)).cartdata();
}
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public void setupTabLayout(TabLayout tabLayout) {
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(mViewpager);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pageAdapter.getTabView(i));
}
tabLayout.requestFocus();
}
}
TabAdapter.class
public class TabAdapter extends FragmentStatePagerAdapter {
private Context mContext;
private List<Fragment> mFragments = new ArrayList<>();
private List<String> mFragmentTitles = new ArrayList<>();
private List<Integer> mFragmentIcons = new ArrayList<>();
public TabAdapter(Context context, FragmentManager fm) {
super(fm);
this.mContext = context;
}
public void addFragment(Fragment fragment, String title, int drawable) {
mFragments.add(fragment);
mFragmentTitles.add(title);
mFragmentIcons.add(drawable);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
public View getTabView(int position) {
View tab = LayoutInflater.from(mContext).inflate(R.layout.customtab, null);
TextView tabText = (TextView) tab.findViewById(R.id.tabText);
ImageView tabImage = (ImageView) tab.findViewById(R.id.tabImage);
tabText.setText(mFragmentTitles.get(position));
tabImage.setBackgroundResource(mFragmentIcons.get(position));
if (position == 0) {
tab.setSelected(true);
}
return tab;
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
Cart.Java
public class Cart extends Fragment {
Button check_out;
TextView subtotal;
ListView cartview;
CartAdapter cartAdapter;
List<JSONParser> cartitems;
SharedPreferences loginPreferences;
SharedPreferences.Editor loginPrefsEditor;
TextView cartstatus,cartempty;
LinearLayout linearlay;
RelativeLayout cartvisible;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View cartfrag = inflater.inflate(R.layout.cart, container, false);
subtotal = (TextView) cartfrag.findViewById(R.id.subtotal);
cartview = (ListView) cartfrag.findViewById(R.id.cartview);
cartstatus = (TextView) cartfrag.findViewById(R.id.cartstatus);
cartempty = (TextView) cartfrag.findViewById(R.id.cartempty);
linearlay = (LinearLayout) cartfrag.findViewById(R.id.linearlay);
cartvisible = (RelativeLayout) cartfrag.findViewById(R.id.cartvisible);
cartitems = new ArrayList<JSONParser>();
cartAdapter = new CartAdapter(getActivity(), cartitems);
cartview.setAdapter(cartAdapter);
check_out = (Button) cartfrag.findViewById(R.id.check_out);
check_out.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cart_check = new Intent(getActivity(), Check.class);
startActivity(cart_check);
}
});
Session cartlogged = new Session(getActivity());
if (cartlogged.isLoggedIn()) {
cartitems.clear();
cartdata();
} else {
cartstatus.setText("Please Login");
}
return cartfrag;
}
void cartdata() {
cartitems.clear();
SharedPreferences customerid = getActivity().getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
String customid = customerid.getString("customerid", "");
String carturl = "http://standardtakeaway.co.uk/json/view_cart.php?userid=" + customid;
Log.d("CartData", carturl);
JsonObjectRequest cartreq = new JsonObjectRequest(Request.Method.GET, carturl, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString("status").equals("empty")) {
cartstatus.setVisibility(View.GONE);
cartempty.setText("Your Cart is Empty");
} else {
JSONArray objarray = response.getJSONArray("items");
for (int i = 0; i < objarray.length(); i++) {
JSONObject cartdataobj = objarray.getJSONObject(i);
linearlay.setVisibility(View.VISIBLE);
cartvisible.setVisibility(View.GONE);
JSONParser parserdata = new JSONParser();
parserdata.setCartquantity(cartdataobj.getString("qty"));
parserdata.setCartbase(cartdataobj.getString("BaseName"));
parserdata.setCartprice(cartdataobj.getString("price"));
cartitems.add(parserdata);
loginPreferences = getActivity().getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
loginPrefsEditor = loginPreferences.edit();
JSONObject subobj = response.getJSONObject("details");
String subtext = subobj.getString("subtotal");
loginPrefsEditor.putString("Price", subtext);
loginPrefsEditor.commit();
subtotal.setText(subtext);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
cartAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "" + error, Toast.LENGTH_SHORT).show();
}
});
cartreq.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(cartreq);
}
public static Cart getInstance(String message) {
Cart cart = new Cart();
Bundle bundle = new Bundle();
bundle.putString("MSG", message);
cart.setArguments(bundle);
return cart;
}
}
CartAdapter.class
public class CartAdapter extends BaseAdapter {
Context context;
TextView quantity, basenamecart, cartprice;
ImageButton delete;
private List<JSONParser> cartitems;
LayoutInflater inflater;
String removequantity, removeitemprice,removebasename;
public CartAdapter(Context context, List<JSONParser> cartitems) {
this.context = context;
this.cartitems = cartitems;
}
#Override
public int getCount() {
return cartitems.size();
}
#Override
public Object getItem(int position) {
return cartitems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.cartitems, parent, false);
quantity = (TextView) convertView.findViewById(R.id.quantity);
basenamecart = (TextView) convertView.findViewById(R.id.basenamecart);
cartprice = (TextView) convertView.findViewById(R.id.cartprice);
delete= (ImageButton) convertView.findViewById(R.id.delete);
final JSONParser dataparser = cartitems.get(position);
quantity.setText(dataparser.getCartquantity());
basenamecart.setText(dataparser.getCartbase());
cartprice.setText(dataparser.getCartprice());
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removequantity=dataparser.getCartquantity();
removebasename=dataparser.getCartbase();
removeitemprice=dataparser.getCartprice();
removecart();
}
});
}
return convertView;
}
private void removecart(){
SharedPreferences customerid=context.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
String removeid=customerid.getString("customerid","");
String removeurl="http://standardtakeaway.co.uk/json/del_cartitems.php?userid="+removeid+"&Item="+removebasename+"&price="+removeitemprice;
Log.d("Remove",removeurl);
final JsonArrayRequest removearray=new JsonArrayRequest(Request.Method.GET, removeurl, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i=0;i<response.length();i++){
Log.d("Remove", String.valueOf(response));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
removearray.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(removearray);
}
}
You need to remove the concerned object from the list cartitems and then call the notifyDataSetChanged() method to notify the any dependent views to refresh itself.
Documentation here
Also, this is not the correct way to implement a BaseAdapter and handle changes in it. Maybe this will help : http://androidadapternotifiydatasetchanged.blogspot.in/
Also, try using the new RecyclerView in order to implement such things. It is available in the support library and definitely a good way to display collections and also makes it easy to add remove items with default animations too. Please read through it. A starting point http://developer.android.com/training/material/lists-cards.html
see added line and updated line.
add make sure only remove item from list if removed successfully from server.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.cartitems, parent, false);
quantity = (TextView) convertView.findViewById(R.id.quantity);
basenamecart = (TextView) convertView.findViewById(R.id.basenamecart);
cartprice = (TextView) convertView.findViewById(R.id.cartprice);
delete= (ImageButton) convertView.findViewById(R.id.delete);
final JSONParser dataparser = cartitems.get(position);
quantity.setText(dataparser.getCartquantity());
basenamecart.setText(dataparser.getCartbase());
cartprice.setText(dataparser.getCartprice());
final int pos =position; // added line
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removequantity=dataparser.getCartquantity();
removebasename=dataparser.getCartbase();
removeitemprice=dataparser.getCartprice();
removecart(pos); //updated line
}
});
}
return convertView;
}
public void updateCartitems(List<JSONParser> newCartitems) {
cartitems.clear();
cartitems.addAll(newCartitems);
this.notifyDataSetChanged();
}
private void removecart(int pos){ // updated line
SharedPreferences customerid=context.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
String removeid=customerid.getString("customerid","");
String removeurl="http://standardtakeaway.co.uk/json/del_cartitems.php?userid="+removeid+"&Item="+removebasename+"&price="+removeitemprice;
Log.d("Remove",removeurl);
final JsonArrayRequest removearray=new JsonArrayRequest(Request.Method.GET, removeurl, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i=0;i<response.length();i++){
Log.d("Remove", String.valueOf(response));
}
cartitems.remove(pos); //added line
updateCartitems(cartitems);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
removearray.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(removearray);
}