Android passing ArrayList<Model> to Fragment from Activity - java

Hi I want to send the data ArrayList<Division> to Fragment class ListContentFragment.
In MainActivity I am making a network call to get the data(JSON) and then parsing it to create ArrayList<Division>, now i want to populate the list view with the data i received (now in ArrayList<Division>)
MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Adding Toolbar to Main screen
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Setting ViewPager for each Tabs
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
// Set Tabs inside Toolbar
TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
// Create Navigation drawer and inlfate layout
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
// Adding menu icon to Toolbar
ActionBar supportActionBar = getSupportActionBar();
if (supportActionBar != null) {
VectorDrawableCompat indicator
= VectorDrawableCompat.create(getResources(), R.drawable.ic_menu, getTheme());
indicator.setTint(ResourcesCompat.getColor(getResources(),R.color.white,getTheme()));
supportActionBar.setHomeAsUpIndicator(indicator);
supportActionBar.setDisplayHomeAsUpEnabled(true);
}
// Set behavior of Navigation drawer
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// Set item in checked state
menuItem.setChecked(true);
// TODO: handle navigation
Toast.makeText(MainActivity.this, "Clicked: " + menuItem.getTitle(), Toast.LENGTH_SHORT).show();
// Closing drawer on item click
mDrawerLayout.closeDrawers();
return true;
}
});
// Adding Floating Action Button to bottom right of main view
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Snackbar.make(v, "Hello Snackbar!",
Snackbar.LENGTH_LONG).show();
}
});
// Network request test with volley
NetworkRequests networkRequest = new NetworkRequests(this);
networkRequest.fetchDummyData();
divisionList = networkRequest.getDivisions();
}
// Add Fragments to Tabs
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
adapter.addFragment(new ListContentFragment(), "List");
adapter.addFragment(new TileContentFragment(), "Tile");
adapter.addFragment(new CardContentFragment(), "Card");
viewPager.setAdapter(adapter);
}
Fragment (currently its hard coded, want to populate with the ArrayList)
public class ListContentFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RecyclerView recyclerView = (RecyclerView) inflater.inflate(
R.layout.recycler_view, container, false);
ContentAdapter adapter = new ContentAdapter(recyclerView.getContext());
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return recyclerView;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public ImageView avator;
public TextView name;
public TextView description;
public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.item_list, parent, false));
avator = (ImageView) itemView.findViewById(R.id.list_avatar);
name = (TextView) itemView.findViewById(R.id.list_title);
description = (TextView) itemView.findViewById(R.id.list_desc);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra(DetailActivity.EXTRA_POSITION, getAdapterPosition());
context.startActivity(intent);
}
});
}
}
/**
* Adapter to display recycler view.
*/
public static class ContentAdapter extends RecyclerView.Adapter<ViewHolder> {
// Set numbers of List in RecyclerView.
private static final int LENGTH = 18;
private final String[] mPlaces;
private final String[] mPlaceDesc;
private final Drawable[] mPlaceAvators;
public ContentAdapter(Context context) {
Resources resources = context.getResources();
mPlaces = resources.getStringArray(R.array.places);
mPlaceDesc = resources.getStringArray(R.array.place_desc);
TypedArray a = resources.obtainTypedArray(R.array.place_avator);
mPlaceAvators = new Drawable[a.length()];
for (int i = 0; i < mPlaceAvators.length; i++) {
mPlaceAvators[i] = a.getDrawable(i);
}
a.recycle();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()), parent);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.avator.setImageDrawable(mPlaceAvators[position % mPlaceAvators.length]);
holder.name.setText(mPlaces[position % mPlaces.length]);
holder.description.setText(mPlaceDesc[position % mPlaceDesc.length]);
}
#Override
public int getItemCount() {
return LENGTH;
}
}
}

If you want to pass an ArrayList to your fragment, then you need to make sure the Model class is implements Parcelable.
Here i can show an example.
public class ObjectName implements Parcelable {
public ObjectName(Parcel in) {
super();
readFromParcel(in);
}
public static final Parcelable.Creator<ObjectName> CREATOR = new Parcelable.Creator<ObjectName>() {
public ObjectName createFromParcel(Parcel in) {
return new ObjectName(in);
}
public ObjectName[] newArray(int size) {
return new ObjectName[size];
}
};
public void readFromParcel(Parcel in) {
Value1 = in.readInt();
Value2 = in.readInt();
Value3 = in.readInt();
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(Value1);
dest.writeInt(Value2);
dest.writeInt(Value3);
}
}
then you can add ArrayList<ObjectName> to a Bundle object.
ArrayList<ObjectName> arraylist = new Arraylist<ObjectName>();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("arraylist", arraylist);
fragment.setArguments(bundle);
After this you can get back this data by using,
Bundle extras = getIntent().getExtras();
ArrayList<ObjectName> arraylist = extras.getParcelableArrayList("arraylist");
At last you can show list with these data in fragment. Hope this will help to get your expected answer.

I was also stuck with the same problem .
You can try this.
Intead of sending the arraylist as bundle to fragment.Make the arraylist to be passed,as public and static in the activity.
public static Arraylist<Division> arraylist;
Then after parsing and adding the data in the arraylist make the call to the fragment.In the fragment you can the use the arraylist as:
ArrayList<Division> list=MainActivity.arraylist;

Related

Convert ListView to RecyclerView

i have a list view in my app.
I want to change it to an recycler view, but even with different tutorials i dont get it.
I was using this: https://www.spreys.com/listview-to-recyclerview/
I failed with the "getView" part here.
Here is my code of the ListActivity and LeagueArrayAdapter.
Thanks for your help.
ListActivity:
public class ListActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private ArrayAdapter adapter;
private final int REQUEST_CODE_EDIT = 1;
private static LeagueDAO leagueDAO;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
leagueDAO = MainActivity.getLeagueDAO();
List<League> allLeagues1 = leagueDAO.getLeagues();
if (allLeagues1.size() == 0) {
leagueDAO.insert(new League("HVM Landesliga 19/20","https://hvmittelrhein-handball.liga.nu/cgi-bin/WebObjects/nuLigaHBDE.woa/wa/groupPage?championship=MR+19%2F20&group=247189"));
allLeagues1 = leagueDAO.getLeagues();
}
adapter = new LeagueArrayAdapter(this, R.layout.league, allLeagues1);
ListView lv = findViewById(R.id.league_list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
registerForContextMenu(lv);
Button btn_league_add = findViewById(R.id.btn_league_add);
btn_league_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ListActivity.this, EditActivity.class);
startActivity(intent);
}
});
}
#Override
public void onCreateContextMenu(ContextMenu contMenu, View v,
ContextMenu.ContextMenuInfo contextmenuInfo) {
super.onCreateContextMenu(contMenu, v, contextmenuInfo);
getMenuInflater().inflate(R.menu.team_list_context_menu, contMenu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo acmi=
(AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
League league = (League)adapter.getItem(acmi.position);
switch (item.getItemId()) {
case R.id.evliconit_edit:
editEntry(league, acmi.position);
return true;
case R.id.evliconit_del:
leagueDAO.delete(league);
adapter.remove(league);
adapter.notifyDataSetChanged();
return true;
default:
return super.onContextItemSelected(item);
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
League team = (League)adapter.getItem(position);
editEntry(team, position);
}
private void editEntry(League league, int position) {
Intent intent = new Intent(this, EditActivity.class);
intent.putExtra("team", league);
intent.putExtra("position", position);
startActivityForResult(intent, REQUEST_CODE_EDIT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == REQUEST_CODE_EDIT && resultCode == RESULT_OK && intent != null) {
Bundle extras = intent.getExtras();
int position = extras.getInt("position");
League league = (League) adapter.getItem(position);
league.setLeague_name(extras.getString("league_name"));
league.setLeague_url(extras.getString("league_url"));
adapter.notifyDataSetChanged();
}
}
#Override
protected void onRestart() {
super.onRestart();
leagueDAO = MainActivity.getLeagueDAO();
List<League> allLeagues1 = leagueDAO.getLeagues();
adapter = new LeagueArrayAdapter(this, R.layout.league, allLeagues1);
ListView lv = findViewById(R.id.league_list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
registerForContextMenu(lv);
}
LeagueArrayAdapter:
public class LeagueArrayAdapter extends ArrayAdapter<League> {
private List<League> leagues;
private Context context;
private int layout;
public LeagueArrayAdapter(Context context, int layout, List<League> leagues) {
super(context, layout, leagues);
this.context = context;
this.layout = layout;
this.leagues = leagues;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
League league = leagues.get(position);
if (convertView == null)
convertView = LayoutInflater.from(context).inflate(layout, null);
TextView tv_name = convertView.findViewById(R.id.tv_name);
TextView tv_url = convertView.findViewById(R.id.tv_url);
tv_name.setText(league.getLeague_name());
tv_url.setText(league.getLeague_url());
return convertView;
}
}
Update: app crashed when opened the activity
public class ListActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private ArrayAdapter adapter;
private final int REQUEST_CODE_EDIT = 1;
private static LeagueDAO leagueDAO;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
leagueDAO = MainActivity.getLeagueDAO();
List<League> allLeagues1 = leagueDAO.getLeagues();
if (allLeagues1.size() == 0) {
leagueDAO.insert(new League("HVM Landesliga 19/20","https://hvmittelrhein-handball.liga.nu/cgi-bin/WebObjects/nuLigaHBDE.woa/wa/groupPage?championship=MR+19%2F20&group=247189"));
allLeagues1 = leagueDAO.getLeagues();
}
// adapter = new LeagueArrayAdapter(this, R.layout.league, allLeagues1);
RecyclerView lv = findViewById(R.id.league_list);
lv.setHasFixedSize(true);
lv.setLayoutManager(new LinearLayoutManager(this));
lv.setAdapter(new LeagueArrayAdapter(allLeagues1));
// lv.setOnItemClickListener(this);
registerForContextMenu(lv);
Button btn_league_add = findViewById(R.id.btn_league_add);
btn_league_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ListActivity.this, EditActivity.class);
startActivity(intent);
}
});
}
I reconstructed your ListView Adapter using RecyclerView.Adapter.
onCreateView is called for every visible container on your screen. If your screen can show 10 rows of data RecyclerView makes 11 - 12 containers (ViewHolder)
onBindView updates those containers with new data when you scroll.
MyViewHolder is the object that holds data about every row of data (container)
static class and bind() function inside to avoid any memory leak in your adapter.
We have access to Context in RecyclerView.Adapter using itemView and parent
itemView is the inflated View for each container (ViewHolder).
Initialize your Views inside ViewHolder's constructor so they get assigned once.
public class LeagueArrayAdapter extends RecyclerView.Adapter<LeagueArrayAdapter.MyViewHolder> {
private ArrayList<League> leagues;
public LeagueArrayAdapter(ArrayList<League> leagues) {
this.leagues = leagues;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return LayoutInflater.from(parent.getContext()).inflate(R.layout.row_league, parent, false);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.bind(leagues.get(position));
}
#Override
public int getItemCount() {
return 0;
}
static class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv_name;
TextView tv_url;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
tv_name = itemView.findViewById(R.id.tv_name);
tv_url = itemView.findViewById(R.id.tv_url);
}
void bind(League league) {
tv_name.setText(league.getLeague_name());
tv_url.setText(league.getLeague_url());
}
}
}
Your Activity:
LinearLayoutManager for a linear layout
GridLayoutManager for a grid layout
setHasFixedSize() enhances your RecyclerView's speed if you are sure the RecyclerView itself won't change width or height.
public class LeagueActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.YOUR_ACTIVITY_LAYOUT_ID);
...
RecyclerView recyclerView = findViewById(R.id.YOUR_RECYCLER_VIEW_ID);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(new LeagueArrayAdapter(SEND_YOUR_ARRAY_OF_LEAGUE));
}
}
I suggest checking the Groupie Lbrary, it works with recyclerView and it makes life much easier for you, here is an example of how you can use it (I'm writing the code in kotlin but it shouldn't be that different from java)
first, add those lines to your Build.gradle (app) file
implementation 'com.xwray:groupie:2.3.0'
implementation 'com.xwray:groupie-kotlin-android-extensions:2.3.0'
then inside your activity create an adapter then set the adapter to your recyclerView
val myAdapter = GroupAdapter<ViewHolder>()
recyclerView.adapter = myAdapter
and just like this you set the adapter to your recyclerView, but you have to create "Items" to put inside the recyclerView. you can create an Item like so
class MyItem: Item() {
override fun getLayout() = R.layout.layout_seen
override fun bind(viewHolder: ViewHolder, position: Int){
}
}
in the getLayout method, you return the layout that you to display inside the recyclerView,
you can use the bind method to do any kind of modifications we want to apply to our layout that we are displaying.
lastly, we can add our items to the adapter this way
myAdapter.add(MyItem())
myAdapter.notifyDataSetChanged()
for more details check the library, in here I just explained how you can simply add an item to your RecyclerView

Recyclerview in fragment inside a viewpager

I wanted to use recyclerview inside a fragment of my 3 fragment viewpager. I wrote the code and it ran perfectly but I don't know why it is too slow.When I swap from one fragment to another it almost takes half minute.Don't know what mistakes I did here.
Main Activity
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar)findViewById(R.id.toolBar);
tabLayout = (TabLayout)findViewById(R.id.tabs);
viewPager = (ViewPager)findViewById(R.id.viewPager);
setSupportActionBar(toolbar);
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragment(new OneFragment(), "One");
viewPagerAdapter.addFragment(new TwoFragment(), "Two");
viewPagerAdapter.addFragment(new ThreeFragment(), "Three");
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
}
Here it is one of my fragment where I tried to implement recyclerview.
Fragment
public class TwoFragment extends Fragment {
public TwoFragment() {
// 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_two, container, false);
OurData ourData = new OurData();
ourData.pic.add(R.drawable.b);
ourData.title.add("Hello");
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.listRecyclerView);
ListAdapter listAdapter = new ListAdapter();
recyclerView.setAdapter((listAdapter));
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
return view;
}
}
public class ListAdapter extends RecyclerView.Adapter {
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return new ListViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((ListViewHolder) holder).bindView(position);
}
#Override
public int getItemCount() {
return OurData.title.size();
}
private class ListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView text;
private ImageView image;
public ListViewHolder(View itemview) {
super(itemview);
text = (TextView) itemview.findViewById(R.id.textF);
image = (ImageView) itemview.findViewById(R.id.imageF);
itemview.setOnClickListener(this);
}
public void bindView(int position) {
text.setText(OurData.title.get(position));
image.setImageResource(OurData.pic.get(position));
}
public void onClick(View view) {
}
}
}
public class OurData {
public static ArrayList<String> title = new ArrayList<String>();
public static ArrayList<Integer> pic = new ArrayList<Integer>();
}
It tooks my whole day thinking what I did wrong. Please help me out!
set your adapter recyclerView.setAdapter((listAdapter));
insise onViewCreated instead of onCreateView
I think the problem is because of one of your Methods.
maybe 'OurData'
and also are you sure of this:
#Override
public int getItemCount() {
return OurData.title.size();
}
also try using Log in each code and see the part that takes time especially 'OurData'

Android passing data while using Activity, Fragment, Listview and Tabs

In my MainActivity I derive an arrayList of data. The trick here is that I am trying to rearrange this data Collection in a listview in different ways according to the tab that is selected for example (alphabetically, chronologically etc) I have the code that does that.
Below is my main activity.
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private FloatingActionButton fab;
private final int PICK = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fp_get_Android_Contacts();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
// calling OnActivityResult with intenet And Some conatct for Identifie
startActivityForResult(intent, PICK);
}
});
}
public class Android_Contact {
public String android_contact_Name = "";
public String android_contact_TelefonNr = "";
public int android_contact_ID = 0;
}
public void fp_get_Android_Contacts() {
ArrayList<Android_Contact> arrayListAndroidContacts = new ArrayList<Android_Contact>();
Cursor cursor_Android_Contacts = null;
ContentResolver contentResolver = getContentResolver();
try {
cursor_Android_Contacts = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
} catch (
Exception ex
)
{
Log.e("Error on contact", ex.getMessage());
}
if (cursor_Android_Contacts.getCount() > 0)
{
while (cursor_Android_Contacts.moveToNext()) {
Android_Contact android_contact = new Android_Contact();
String contact_id = cursor_Android_Contacts.getString(cursor_Android_Contacts.getColumnIndex(ContactsContract.Contacts._ID));
String contact_display_name = cursor_Android_Contacts.getString(cursor_Android_Contacts.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
android_contact.android_contact_Name = contact_display_name;
int hasPhoneNumber = Integer.parseInt(cursor_Android_Contacts.getString(cursor_Android_Contacts.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI
, null
, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?"
, new String[]{contact_id}
, null);
while (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
android_contact.android_contact_TelefonNr = phoneNumber;
}
phoneCursor.close();
}
arrayListAndroidContacts.add(android_contact);
}
Collections.reverse(arrayListAndroidContacts);
ListView listView_Android_Contacts = (ListView) findViewById(R.id.listview_Android_Contacts);
Adapter_for_Android_Contacts adapter = new Adapter_for_Android_Contacts(this, arrayListAndroidContacts);
listView_Android_Contacts.setAdapter(adapter);
}
}
public class Adapter_for_Android_Contacts extends BaseAdapter {
Context mContext;
List<Android_Contact> mList_Android_Contacts;
public Adapter_for_Android_Contacts(Context mContext, List<Android_Contact> mContact) {
this.mContext = mContext;
this.mList_Android_Contacts = mContact;
}
public int getCount() {
return mList_Android_Contacts.size();
}
public Object getItem(int position) {
return mList_Android_Contacts.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = View.inflate(mContext, R.layout.contactlist_android_items, null);
TextView textview_contact_Name = (TextView) view.findViewById(R.id.textview_android_contact_name);
textview_contact_Name.setText(mList_Android_Contacts.get(position).android_contact_Name);
view.setTag(mList_Android_Contacts.get(position).android_contact_Name);
return view;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Tab2AZ tab2 = new Tab2AZ();
return tab2;
case 1:
Tab1Recents tab1 = new Tab1Recents();
return tab1;
case 2:
Tab3Location tab3 = new Tab3Location();
return tab3;
case 3:
Tab4Groups tab4 = new Tab4Groups();
return tab4;
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "A-Z";
case 1:
return "RECENT";
case 2:
return "LOCATION";
case 3:
return "TAGS";
}
return null;
}
}
}
To save you time the fp_get_Android_Contacts() method grabs the arraylist, then uses the adapter to put the content in the listview that is in the main activity xml. The result is that all the tabs visually display the same view. (Because the MainActivity's Listview is covering the fragment's listviews) I'm really just trying to get the content retrieved from the fp_get_Android_Contacts() method to display on one fragment at a time. Ive looked into using bundles, parcelables, intents and recently interfaces however successful implementation has been tough to achieve given my experience level perhaps. Would appreciate a specific approach instead of a reference to read something as I have done a lot of research and tried many things already.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.tab1_recent, container, false);
return rootView;
}
}
Create Interface
public interface FragmentListener {
void setArrayListAndroidContacts(List<Android_Contact> contacts);
List<Android_Contact> getArrayListAndroidContacts();
}
Let your MainActivity implement this interface
public class MainActivity extends AppCompatActivity implements FragmentListener {
//global field
private List<Android_Contact> arrayListAndroidContacts;
...
//your code
...
//override methods of interface
#Override
void setArrayListAndroidContacts(List<Android_Contact> contacts){
this.arrayListAndroidContacts = contacts;
}
#Override
List<Android_Contact> getArrayListAndroidContacts(){
return this.arrayListAndroidContacts;
}
Your fragment
public class YourFragment extends Fragment{
private FragmentListener mListener;
...
//in onCreateView
//this will give you list
mListener.getArrayListAndroidContacts();
....
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof FragmentListener) {
mListener = (FragmentListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement FragmentListener");
}
}
}
Another method is just create public getter setter of arrayListAndroidContacts in MainActivity and in your fragment use (MainActivity getActivity()).getArrayListAndroidContacts() to get the list. I would prefer interface method because of reusability.
Also why create viewpager, fragments if you want to rearrange data by a filter selection(sort by alpha,chrono) without any view changes.
Just add filter menu actions in floatingmenu/toolbarsidemenu, recyclerview(any list view) and customadapter for it in Mainactivity. Depending on the filter selection reorder your contacts list and notifydatasetchanged will do all your work.
Go for tabs if you want to have category of contacts like favorites, business etc.. to be displayed in single screen.
Suggestion:-
Kindly separate your custom BaseAdapter code from MainActivity for better source code maintenance .
You should be having multiple tabs and corresponding Fragments for those tabs. Right ?
I can not find that in your code.
For every fragment generate a separate .xml file and create separate listview in each fragment and pass the data in each fragment accordingly. And you are done.
e.g., for alphabetically : Create fragment AlphabetSortFragment and for the same create a .xml file and a listview or recycler view in it.

I'm getting the same cardview images on my three tab layouts

I'm trying to create a cardview album recycler view and as I was finishing up my code I found out that my program is displaying the same cardview for all three tab layouts. I want to display different cardview album for different tab layouts.Any help please!! Here is my program output.
program output
private RecyclerView recyclerView;
private AlbumAdapter adapter;
private List<Album> albumList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
albumList = new ArrayList<>();
adapter = new AlbumAdapter(this, albumList);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 1);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
prepareAlbums();
try
{
Glide.with(this).load(R.drawable.cover);
} catch (Exception e)
{
e.printStackTrace();
}
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(MyFragment.newInstance("Home Fragment"), "Featured");
adapter.addFragment(MyFragment.newInstance("Events Fragment"), "Just Arrived");
adapter.addFragment(MyFragment.newInstance("Settings Fragment"), "Upcoming");
adapter.addFragment(MyFragment.newInstance("Settings Fragment"), "Upcoming");
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
//adding viewpager to the tab-layout
tabLayout.setupWithViewPager(viewPager);
/**
* To have icons along with text but these icons will not change on selection of the tabs.
* So use the selector for the icons to change.
*/
tabLayout.getTabAt(0).setIcon(R.drawable.ic_menu_camera);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_menu_share);
// using selector for icons
tabLayout.getTabAt(2).setIcon(R.drawable.ic_menu_slideshow);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
/**
* Adding few albums for testing
*/
private void prepareAlbums() {
int[] covers = new int[]{
R.drawable.album1,
R.drawable.album2,
R.drawable.album3,
R.drawable.album4,
R.drawable.album5,
R.drawable.album6,
R.drawable.album7,
R.drawable.album8,
R.drawable.album9,
R.drawable.album10,
R.drawable.album11
};
Album a = new Album("hello", "Price: $2",covers[0]);
albumList.add(a);
a = new Album("Sugar", "Price: $6", covers[1]);
albumList.add(a);
a = new Album("Bon", "Price: $6", covers[2]);
albumList.add(a);
a = new Album("The lazy","Price: $7", covers[3]);
albumList.add(a);
a = new Album("The Cranberries", "Price: $3", covers[4]);
albumList.add(a);
a = new Album("West", "Price: $2", covers[5]);
albumList.add(a);
a = new Album("Black ", "Price: $2", covers[6]);
albumList.add(a);
a = new Album("Viva", "Price: $2", covers[7]);
albumList.add(a);
a = new Album("Cardigans", "Price: $12", covers[8]);
albumList.add(a);
a = new Album("Dolls", "Price: $2", covers[9]);
albumList.add(a);
adapter.notifyDataSetChanged();
}
static class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
//return mFragmentList.get(position);
switch (position) {
case 0:
MyFragment tab1 = new MyFragment();
return tab1;
case 1:
myfrag2 tab2 = new myfrag2();
return tab2;
case 2:
myfrag3 tab3 = new myfrag3();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return 3;
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
Here's my albumAdapter class
public class AlbumAdapter extends RecyclerView.Adapter<AlbumAdapter.MyViewHolder> {
private Context mContext;
private List<Album> albumList;
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);
}
}
public AlbumAdapter(Context mContext, List<Album> albumList) {
this.mContext = mContext;
this.albumList = albumList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_layout, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
Album album = albumList.get(position);
holder.title.setText(album.getName());
holder.count.setText(album.getPrice());
// loading album cover using Glide library
Glide.with(mContext).load(album.getThumbnail()).into(holder.thumbnail);
holder.overflow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showPopupMenu(holder.overflow);
}
});
}
/**
* 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();
}
/**
* 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();
}
}
My recyclerAdapter class
public class RecyclerAdapter extends RecyclerView.Adapter {
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
}
#Override
public int getItemCount() {
return 0;
}
}
Here's my first fragment class
public class MyFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_layout, container, false);
return v;
}
public static MyFragment newInstance(String text) {
MyFragment f = new MyFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
Here's my second fragment
public class myfrag2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_layout2, container, false);
return v;
}
}
here's my third frag
public class myfrag3 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_layout3, container, false);
return v;
}
}

Sliding Tabs with RecycleView Fragments and Swipe to Refresh

i'm having some issues implementing a Sliding Tabs activity that contains 2 Fragments and a Swipe Down to Refresh layout, namely implementing the Swipe Down to Refresh part (the rest is working just fine).
First here are my XML files.
The Main Activity XML , which contains the ViewPager wrapped in an SwipeRefreshLayout :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.popal.soul.MovieListActivityTEST">
<com.example.popal.soul.SlidingTabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="2dp"
android:background="#color/ColorPrimary"/>
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipeContainer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="1">
</android.support.v4.view.ViewPager>
</android.support.v4.widget.SwipeRefreshLayout>
And the first tab XML , one of the 2 tabs (both are similar, so i`ll only post one)
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.v7.widget.RecyclerView
android:id="#+id/cardList"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
Now, my main activity, which handles the ViewPager, Adapter an the SlidingTabsLayout.
public class MovieListActivityTEST extends AppCompatActivity {
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Home","Events"};
int Numboftabs =2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_list_activity_test);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true);
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
}
And finally, my fragment for the first Tab
public class Tab1 extends Fragment {
public MovieListAdapter movieListAdaptor;
public RecyclerView recycleList;
private SwipeRefreshLayout swipeContainer;
private List<MovieListAdapter.MovieDetails> movieList = new ArrayList<MovieListAdapter.MovieDetails>();
private ProgressBar progressBar;
private final static String MOVIES_POST_REQUEST ="//Long String, Edited out since it`s not relevant"
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1, container, false);
recycleList = (RecyclerView) v.findViewById(R.id.cardList);
progressBar = (ProgressBar) v.findViewById(R.id.progress_bar);
progressBar.setVisibility(View.VISIBLE);
swipeContainer = (SwipeRefreshLayout) v.findViewById(R.id.swipeContainer);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recycleList.setLayoutManager(llm);
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
movieListAdaptor.clear();
new Send_data_to_server().execute(MOVIES_POST_REQUEST);
swipeContainer.setRefreshing(false);
}
});
new Send_data_to_server().execute(MOVIES_POST_REQUEST);
return v;
}
The issue is, i'm getting a NULL Pointer Exception at swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {...} method, which i guess is because the Swipe-to-Refresh layout is in the main activity XML, and not the tabs fragment. So what is the proper way to implement this ? I also tried implementing a Swipe to refresh layout in one of the Tabs XML instead of wrapping the ViewPager in it, like above, but it would crash when swiping from tab to another.
Here`s the code from the entire fragment in Tab1, for tobs answer below
public class MoviesTabFragment extends Fragment implements Refreshable {
public MovieListAdapter movieListAdaptor;
public RecyclerView recycleList;
//private SwipeRefreshLayout swipeContainer;
public List<MovieListAdapter.MovieDetails> movieList = new ArrayList<MovieListAdapter.MovieDetails>();
public ProgressBar progressBar;
public final static String MOVIES_POST_REQUEST ="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1, container, false);
recycleList = (RecyclerView) v.findViewById(R.id.cardList);
progressBar = (ProgressBar) v.findViewById(R.id.progress_bar);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recycleList.setLayoutManager(llm);
new Send_data_to_server().execute(MOVIES_POST_REQUEST);
return v;
}
#Override
public void refresh() {
new Send_data_to_server().execute(MOVIES_POST_REQUEST);
}
public class Send_data_to_server extends AsyncTask<String, Void, String> {
private String data_poster;
private String data_fanart;
// protected void onPreExecute() {
// progressBar.setVisibility(View.VISIBLE);
// }
protected String doInBackground(String... params)
{
String jason_data = params[0];
HttpClient http_con = new HttpClient();
String output_from_server = http_con.establish_con(jason_data);
Log.i("DataFromServer", output_from_server);
JSONObject json_Obj = null;
JSONObject child_obj = null; //creating the "result" object in the main JSON Object
try {
json_Obj = new JSONObject(output_from_server);
child_obj = create_subObject("result", json_Obj);
JSONArray jsonArray = child_obj.optJSONArray("movies");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String title_data = jsonObject.optString("label").toString();
String plot_data = jsonObject.optString("plot").toString();
String year_data = jsonObject.optString("year").toString();
String movie_id_data = jsonObject.optString("movieid").toString();
String imdb_score = jsonObject.optString("rating").toString();
String imdb_score_short = imdb_score.substring(0, 3);
JSONObject child_obj2 = create_subObject("art", jsonObject);
data_poster = child_obj2.optString("poster").toString();
data_fanart = child_obj2.optString("fanart").toString();
JSONEncodePosterFanart encodePosterFanart = new JSONEncodePosterFanart();
String jason_dataPoster = encodePosterFanart.GetPosterFanartEncodedURL(data_poster);
String jason_dataFanart = encodePosterFanart.GetPosterFanartEncodedURL(data_fanart);
HttpClient http = new HttpClient();
String output_from_serverPoster = http.establish_con(jason_dataPoster);
HttpClient http2 = new HttpClient();
String output_from_serverFanart = http2.establish_con(jason_dataFanart);
JSONPosterFanart poster_fanart = new JSONPosterFanart();
String post_dl = poster_fanart.GetPosterFanart(output_from_serverPoster);
JSONPosterFanart poster_fanart2 = new JSONPosterFanart();
String fanart_dl = poster_fanart2.GetPosterFanart(output_from_serverFanart);
if (null == movieList) {
movieList = new ArrayList<MovieListAdapter.MovieDetails>();
}
MovieListAdapter.MovieDetails item = new MovieListAdapter.MovieDetails(title_data+" ("+year_data+")", post_dl, fanart_dl,plot_data,movie_id_data,imdb_score_short);
movieList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
return output_from_server;
}
protected void onPostExecute(String output_from_server) {
super.onPostExecute(output_from_server);
//progressBar.setVisibility(View.INVISIBLE);
movieListAdaptor = new MovieListAdapter(getActivity(), movieList);
recycleList.setAdapter(movieListAdaptor);
}
private JSONObject create_subObject(String tagName, JSONObject jObj) throws JSONException {
JSONObject subObj = jObj.getJSONObject(tagName); //getJSONObject returns the value from tagName (in our case jason_Obj that is being passed ar a param)
return subObj;
}
}
}
And the RecycleView adapter:
public class MovieListAdapter extends RecyclerView.Adapter<MovieListAdapter.MovieViewHolder> {
public List<MovieDetails> movieList;
private Context mContext;
public MovieListAdapter(Context mContext, List<MovieDetails> movieList) {
this.mContext = mContext;
this.movieList = movieList;
}
#Override
public int getItemCount() {
return movieList.size();
}
public void clear() {
movieList.clear();
notifyDataSetChanged();
}
#Override
public MovieViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.card_layout_movies_list, viewGroup, false);
return new MovieViewHolder(itemView);
}
#Override
public void onBindViewHolder(MovieViewHolder movieViewHolder, int i) {
MovieDetails mdet = movieList.get(i);
String fanart = "http://192.168.1.128/"+mdet.getImageViewFanart();
String poster = "http://192.168.1.128/"+mdet.getImageViewPoster();
Log.i("fanart", fanart);
Log.i("poster", poster);
movieViewHolder.vTitle.setText(mdet.Title);
Picasso.with(mContext).load(poster)
.resize(500, 746)
.error(R.drawable.poster_placeholder)
.placeholder(R.drawable.poster_placeholder)
.into(movieViewHolder.vPoster);
Picasso.with(mContext).load(fanart)
.resize(960, 540)
.error(R.drawable.fanart_placeholder)
.placeholder(R.drawable.fanart_placeholder)
.into(movieViewHolder.vFanart);
movieViewHolder.vplot = mdet.getPlot();
movieViewHolder.vmovie_id = mdet.getMovie_id();
}
public class MovieViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected TextView vTitle;
protected ImageView vPoster;
protected ImageView vFanart;
protected String vplot;
protected String vmovie_id;
protected String vimdb_score;
public MovieViewHolder(View v)
{
super(v);
vplot = new String();
vmovie_id = new String();
vimdb_score = new String();
vTitle = (TextView) v.findViewById(R.id.title);
vPoster = (ImageView) v.findViewById(R.id.imageViewPoster);
vFanart = (ImageView) v.findViewById(R.id.imageViewFanart);
v.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int position = getLayoutPosition();
MovieDetails mov = movieList.get(position);
Intent intent = new Intent(mContext, MovieDetailsPageActivity.class);
Bundle bundle = new Bundle();
bundle.putString("movieid", mov.getMovie_id());
bundle.putString("plot", vplot);
bundle.putString("fanart_path", mov.getImageViewFanart());
bundle.putString("imdb_score", mov.getImdb_score());
intent.putExtras(bundle);
mContext.startActivity(intent);
}
}
public static class MovieDetails {
protected String Title;
protected String imageViewPoster;
protected String imageViewFanart;
protected String plot;
protected String movie_id;
protected String imdb_score;
public MovieDetails(String Title, String imageViewPoster,String imageViewFanart, String plot, String movie_id ,String imdb_score)
{
this.Title = Title;
this.imageViewPoster = imageViewPoster;
this.imageViewFanart = imageViewFanart;
this.plot = plot;
this.movie_id = movie_id;
this.imdb_score = imdb_score;
}
public String getTitle() {return Title;}
public String getImageViewPoster() {
return imageViewPoster;
}
public String getImageViewFanart() {
return imageViewFanart;
}
public String getPlot() {return plot;}
public String getMovie_id() {return movie_id;}
public String getImdb_score() {return imdb_score;}
}
}
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[];
int NumbOfTabs;
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
#Override
public Fragment getItem(int position) {
if(position == 0)
{
MoviesTabFragment moviesTabFragment = new MoviesTabFragment();
return moviesTabFragment;
}
else
{
TVShowsTabFragment TVShowsTabFragment = new TVShowsTabFragment();
return TVShowsTabFragment;
}
}
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
#Override
public int getCount() {
return NumbOfTabs;
}
You're getting the NullPointerException because you inflate your fragment layout from R.layout.tab_1 which does not contain a SwipeRefreshLayout.
If you want the layout to be the parent of your ViewPager, I would recommend you to move your code which manages the RefreshLayout to the MainActivity:
public class MovieListActivityTEST extends AppCompatActivity {
ViewPager pager;
ViewPagerAdapter adapter;
SwipeRefreshLayout refreshLayout;
SlidingTabLayout tabs;
CharSequence Titles[]={"Home","Events"};
int Numboftabs =2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_list_activity_test);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true);
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
// Assign your refresh layout
refreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeContainer);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Refreshable r = (Refreshable) adapter.getItemAt(pager.getCurrentItem());
r.refresh();
}
});
}
where each of your tab fragments implements a Refreshable interface:
public interface Refreshable {
void refresh();
}
and your adapter keeps track on all fragments:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
// list that keeps references to all attached Fragments
private SparseArray<Fragment> pages = new SparseArray<>();
...
public Fragment getItem(int position) {
Fragment f;
if(position == 0) {
...
} else { ... }
// add fragment to the list
pages.put(position, f);
}
public void destroyItem(ViewGroup container, int position, Object object) {
// remove fragment from list if it existed
if(pages.indexOfKey(position) >= 0) {
pages.remove(position);
}
super.destroyItem(container, position, object);
}
// return the attached Fragment that is associated with the given position
public Fragment getItemAt(int position) {
return pages.get(position);
}
}

Categories

Resources