NullPointerException notifydatasetchanged() - java

I have a main activity with a View Pager and a Spinner. When I change the spinner, i want the fragments in the ViewPager to update to use new data.
I have tried to communicate from the Activity to the Fragment when a selection has been made in the Spinner but I keep getting a NullPointerException.
i call the updateListView() method from the Activity whenever the Spinner selection has been confirmed. The commented line of code also causes it to crash.
ListFragment lf = (ListFragment) mSectionsPagerAdapter.getItem(0);
lf.updateListView();
Here is my code
public class ListFragment extends Fragment {
ArrayList<Psalm> psalms;
ListViewAdapter adapter;
View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
v = inflater.inflate(R.layout.fragment_list, parent, false);
psalms = GlobalSingleton.get(getActivity()).getPsalms().getPsalms();
adapter = new ListViewAdapter(getActivity(), psalms);
ListView l = (ListView) v.findViewById(R.id.fragmentListListView);
l.setAdapter(adapter);
return v;
}
public void updateListView(){
psalms = GlobalSingleton.get(getActivity()).getPsalms().getPsalms();
System.out.println("HERE");
((ListViewAdapter) ((ListView) v.findViewById(R.id.fragmentListListView)).getAdapter()).notifyDataSetChanged();
//adapter.notifyDataSetChanged();
}
}
main activity
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
String[] files = getAssets().list("");
ArrayList<Psalm> singPsalms = new ArrayList<Psalm>();
ArrayList<Psalm> scottishPsalter = new ArrayList<Psalm>();
for(String s: files){
if(s.split("_")[0].equals("SingPsalms")){
singPsalms.add(new Psalm(s.split("_")[1], s.split("_")[2], s.split("_")[3].replace(".txt", "")));
} else if(s.split("_")[0].equals("ScottishPsalter")){
scottishPsalter.add(new Psalm(s.split("_")[1] , s.split("_")[2], s.split("_")[3].replace(".txt", "")));
}
}
Collections.sort(singPsalms, new PsalmComparator());
GlobalSingleton.get(this).setSingPsalms(new Psalmody("Sing Psalms", singPsalms));
GlobalSingleton.get(this).setScottishPsalter(new Psalmody("Scottish Psalter", scottishPsalter));
GlobalSingleton.get(this).setSelectedPsalmody("Scottish Psalter");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Adapter
Spinner psalter = (Spinner) findViewById(R.id.spinner1);
SpinnerAdapter adapter = ArrayAdapter.createFromResource(this, R.array.psalter, android.R.layout.simple_spinner_dropdown_item);
psalter.setAdapter(adapter);
psalter.setOnItemSelectedListener( new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selected = parent.getItemAtPosition(position).toString();
if (!selected.equals(GlobalSingleton.get(getApplicationContext()).getSelectedPsalmody())){
GlobalSingleton.get(getApplicationContext()).setSelectedPsalmody(selected);
System.out.println("HERE");
ListFragment lf = (ListFragment) mSectionsPagerAdapter.getItem(0);
lf.updateListView();
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = null;
if (position == 0){
fragment = new ListFragment();
} else {
fragment = new GridFragment();
}
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return "List".toUpperCase(l);
case 1:
return "Grid".toUpperCase(l);
case 2:
return "Metre Seperated".toUpperCase(l);
}
return null;
}
}
}

Use same object of ListView on which you are calling setAdapter in onCreateView for calling notifyDataSetChanged as:
....
l = (ListView) v.findViewById(R.id.fragmentListListView);
l.setAdapter(adapter);
return v;
}
ListView l;
public void updateListView(){
//....
l.getAdapter()).notifyDataSetChanged();
//adapter.notifyDataSetChanged();
}

try below code. do not use view and use member listview.
public class ListFragment extends Fragment {
ArrayList<Psalm> psalms;
ListViewAdapter adapter;
ListView l;
View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
v = inflater.inflate(R.layout.fragment_list, parent, false);
psalms = GlobalSingleton.get(getActivity()).getPsalms().getPsalms();
adapter = new ListViewAdapter(getActivity(), psalms);
l = (ListView) v.findViewById(R.id.fragmentListListView);
l.setAdapter(adapter);
return v;
}
public void updateListView(){
psalms = GlobalSingleton.get(getActivity()).getPsalms().getPsalms();
System.out.println("HERE");
if(l != null){
l.getAdapter()).notifyDataSetChanged();
}
}

Related

Java android access of member fields of inner class in outer class

public class chapterIndexFragment extends Fragment implements view.OnClickListener,parsexml.AsyncResponse{
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "xml";
//private static final String ARG_PARAM2 = "param2";
private XmlResourceParser xrp;
private View rootview;
private OnFragmentInteractionListener mListener;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
public chapterIndexFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment chapterIndexFragment.
*/
// TODO: Rename and change types and number of parameters
public static chapterIndexFragment newInstance(int xmlid) {
chapterIndexFragment fragment = new chapterIndexFragment();
Bundle args = new Bundle();
args.putInt(ARG_PARAM1,xmlid);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
xrp = getResources().getXml(getArguments().getInt(ARG_PARAM1));
//Async Task.
parsexml pxml = new parsexml(this);
pxml.execute(xrp);
}
}
#Override
public void postProgress(String progress) {
// Why this does not resolve ????
mAdapter.mDataset
}
#Override
public void onFinish(Boolean result) {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootview = inflater.inflate(R.layout.fragment_recycler_view, container, false);
mRecyclerView = (RecyclerView) rootview.findViewById(R.id.recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
// When coming back to this fragment from another fragment with back button. Although view hierarchy is to
//be built again but Adapter will have its data preserved so dont initialize again.
//String[] TempData = new String[]{"One","Two","three","four"};
if(mAdapter == null)
mAdapter = new MyAdapter();
mRecyclerView.setAdapter(mAdapter);
return rootview;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
toolbar.setTitle("Title");
toolbar.setNavigationIcon(R.drawable.ic_menu_hamburger);
//toolbar navigation button (Home Button\Hamburger button) at the start of the toolbar.
toolbar.setNavigationOnClickListener(this);
//Toolbar menu item click listener.
//toolbar.setOnMenuItemClickListener(this);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onClick(View view) {
int id = view.getId();
switch(id)
{
case -1: // Toolbar's Navigation button click retruns -1. Hamburger icon.
if (view instanceof ImageView)
{
if (((MainActivity)getActivity()).drawer.isDrawerOpen(GravityCompat.START))
{
((MainActivity)getActivity()).drawer.closeDrawer(GravityCompat.START);
}
else
{
((MainActivity)getActivity()).drawer.openDrawer(GravityCompat.START);
}
}
break;
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
class MyAdapter extends RecyclerView.Adapter implements MyViewHolder.IItemClickListener{
private ArrayList<String> mDataset;
// Provide a suitable constructor (depends on the kind of dataset)
MyAdapter(){
if(mDataset == null)
{
mDataset = new ArrayList<String>();
}
}
// Create new views (invoked by the layout manager)
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycler_viewholder,parent,false);
// set the view's size, margins, paddings and layout parameters
MyViewHolder vh = new MyViewHolder(v,this);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
MyViewHolder vh = (MyViewHolder)holder;
vh.mtv_Title.setText(mDataset.get(position));
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.size();
}
//MyViewHolder.IItemClickListener
#Override
public void onItemClick(View view, int position) {
}
}
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
// each data item is just a string in this case
TextView mtv_Title;
IItemClickListener mItemClickListener;
//View.OnClickListener
#Override
public void onClick(View view) {
mItemClickListener.onItemClick(view,getAdapterPosition());
}
interface IItemClickListener
{
void onItemClick(View view, int position);
}
MyViewHolder(View v,IItemClickListener itemClickListener) {
super(v);
mtv_Title = (TextView)v.findViewById(R.id.tv_title);
mItemClickListener = itemClickListener;
v.setOnClickListener(this);
}
}
}
In #Override
public void postProgress(String progress) {
// Why this does not resolve ????
mAdapter.mDataset
}
You should be aware of that,
private members can't be accessed via dot notation. To access them we use getter/setter methods.
You have to make a public function to get them, add this method in you inner class,
public ArrayList<String> getDataSet() {
return mDataSet;
}
Also you should change as pointed by #android_hub
private RecyclerView.Adapter mAdapter;
should be private
private MyAdapter mAdapter;

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.

add fragment to pager adapter on button click

I have a tabbed activity with 1 fragment, this fragment has a button, i want when i click the button it create a new fragment and i can swipe between the two fragments
this is the main activity
public class ActivityBeamRec extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
public static CustomViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_beam_rec);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (CustomViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setPagingEnabled(false);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0 : return PlaceholderFragment.newInstance(position + 1);
// case 1 : return the new fragment ;
}
return null;
}
#Override
public int getCount() {
return 1 ;
}
}
}
this is the fragment i have.
public class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_activity_beam_rec, container, false);
final EditText etxb;
etxb = (EditText)rootView.findViewById(R.id.editText);
final Button buDesign = (Button)rootView.findViewById(R.id.buDesign);
buDesign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double b;
b = Double.valueOf(etxb.getText().toString());
\\here i want the button to create the second fragment and pass the variable d to it
ActivityBeamRec.mViewPager.setPagingEnabled(true); // this is to enable the siwpe between the fragments
ActivityBeamRec.mViewPager.setCurrentItem(2); // ths is to set the new fragment as the current view
}
});
return rootView;
}
}
the second fragment should go through on create view stage after the button is pressed, and please tell where i put each code if there is a way to do this.
ActivityBeamRec:
public class ActivityBeamRec extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#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);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
// This list holds the fragments for the pages displayed by view pager.
private List < Fragment > fragments = new ArrayList < Fragment > ();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
// Add the first fragment:
fragments.add(PlaceholderFragment.newInstance(1));
}
private void addFragment(Fragment fragment) {
fragments.add(fragment);
// Notify view pager that the contents of the adapter has changed and that it needs to update
// its pages:
notifyDataSetChanged();
// Since content of view pager has changed, re-wire tab layout:
tabLayout.setupWithViewPager(mViewPager);
// Set the current page in the view pager to the last added fragment:
mViewPager.setCurrentItem(fragments.size() - 1);
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
// Set the tab title as the number of the current section:
return "SECTION " + (position + 1);
}
}
/**
* Adds a new fragment (page) to the view pager.
* This method can either be public or package-private (without any modifier) depending on the package
* of 'PlaceholderFragment'. Since you're new to Java please refer the link to access modifiers below.
*
* #param fragment the fragment to be added to the view pager
**/
public void addFragment(Fragment fragment) {
mSectionsPagerAdapter.addFragment(fragment);
}
/**
* Returns the number of the next section (page) to be added.
*
* #return the next section number
*/
public int getNextSectionNumber() {
return mSectionsPagerAdapter.getCount() + 1;
}
}
PlaceholderFragment:
public class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_activity_beam_rec, container, false);
final EditText etxb;
etxb = (EditText) rootView.findViewById(R.id.editText);
final Button buDesign = (Button) rootView.findViewById(R.id.buDesign);
buDesign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double b;
b = Double.valueOf(etxb.getText().toString());
//here i want the button to create the second fragment and pass the variable d to it
int nextSectionNumber = ((ActivityBeamRec) getActivity()).getNextSectionNumber();
((ActivityBeamRec) getActivity()).addFragment(PlaceholderFragment.newInstance(nextSectionNumber));
}
});
return rootView;
}
}
When the button in the fragment is clicked the following things occur in sequence:
addFragment() method of parent activity is called by passing the fragment instance to be added. This public method is used to access the private member mSectionsPagerAdapter of parent activity. We can do away with this method if mSectionsPagerAdapter is made public or package-private.
SectionsPagerAdapter adds the passed-in fragment to its list of fragments and then notifies the view pager that its data set has changed.
TabLayout is refreshed to accommodate the new fragment (page).
Finally the view pager is made to scroll to the added fragment using the setCurrentItem() method.
Reference:
Java Access Control Modifiers
List Data Structure in Java
In your SectionsPagerAdapter
private ArrayList<Fragment> fragments = new ArrayList<>();
#Override
public int getCount() {
return fragments.size();
}
#Override
public Fragment getItem(int position) {
if(position<fragments.size())
return fragments.get(position);
throw new NullPointerException("No Fragment with this position found.");
}
public void addFragment(Fragment newFragment){
fragments.add(newFragment);
}
In the MainActivity before setting the adapter with mViewPager.setAdapter(mSectionsPagerAdapter); add your first fragment(the PlaceHolder in your case). (or do it in the SectionPagerAdapter's constructor).
And then in your OnClickListener call the SectionPagerAdapter's addFragment method.
EDIT: In MainActivity:
mSectionsPagerAdapter.addFragment(PlaceholderFragment.newInstance(0));
mSectionsPagerAdapter.setAdapter(mSectionsPagerAdapter);

Custom ListView in Viewpager

This is my page:
package[...]
import [...]
public class Home extends FragmentActivity {
ViewPager mViewPager;
ListView list;
row_video_Adapter adapter;
public Home CustomListView = null;
public ArrayList<ModelloLista> CustomListViewValuesArr = new ArrayList<ModelloLista>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// ListView
CustomListView = this;
/******** Take some data in Arraylist ( CustomListViewValuesArr ) ***********/
setListData();
Resources res =getResources();
list= (ListView)findViewById(R.id.section_label); // List defined in XML ( See Below )
/**************** Create Custom Adapter *********/
adapter=new row_video_Adapter(CustomListView, CustomListViewValuesArr,res);
list.setAdapter(adapter);
}
/****** Function to set data in ArrayList *************/
public void setListData(){
final ModelloLista sched = new ModelloLista();
sched.setTitolo("Video 1");
sched.setImmagine("video_preview");
sched.setUrl("http:\\www.com");
CustomListViewValuesArr.add(sched);
}
/***************** This function used by adapter ****************/
public void onItemClick(int mPosition){
ModelloLista tempValues = ( ModelloLista ) CustomListViewValuesArr.get(mPosition);
// SHOW ALERT
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 5 total pages.
return 5;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
[...]
}
return null;
}
}
public static class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home_dummy,
container, false);
//TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
switch(getArguments().getInt(ARG_SECTION_NUMBER)){
case 1:
//dummyTextView.setText("text 1");
break;
case 2:
[...]
}
return rootView;
}
}
}
How can I put my Custom ListView in a fragment?
I tried to move the code in the switch(getArguments().getInt(ARG_SECTION_NUMBER)){ but there were many errors.
What should I do?

Adding Three Fragments Throws IllegalStateException

I used the generated activity with swipe views and title strip. My code worked with two fragments per activity, however when I add three it force closes.
The error is:
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. fragment
Here is my activity class MainMenu:
//imports
public class MainMenu extends FragmentActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide fragments for each of the
* sections. We use a {#link android.support.v4.app.FragmentPagerAdapter} derivative, which will
* keep every loaded fragment in memory. If this becomes too memory intensive, it may be best
* to switch to a {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
// Create the adapter that will return a fragment for each of the three primary sections
// of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main_menu, menu);
return true;
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
* sections of the app.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new Fragment();
Bundle args = new Bundle();
if(i == 0){
fragment = new InsertCity();
}else if(i == 1){
fragment = new AddFlight();
}else if(i == 2){
fragment = new AddFlight();
}
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0: return getString(R.string.title_section1).toUpperCase();
case 1: return getString(R.string.title_section2).toUpperCase();
case 2: return getString(R.string.title_section3).toUpperCase();
}
return null;
}
}
}
Each fragment is almost identicle so I will only include one of them.
Here is my InsertCity class:
public class InsertCity extends Fragment {
private LinearLayout ll;
public InsertCity() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ll = new LinearLayout(getActivity());
ll.setOrientation(LinearLayout.VERTICAL);
TextView usernameInstruction = new TextView(getActivity());
ll.addView(usernameInstruction);
Button btn = new Button(getActivity());
btn.setText("Create Backup");
btn.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
}
});
ll.addView(btn);
// setContentView(ll);
}
// #Override
// public void onDestroyView() {
// super.onDestroyView();
// ViewGroup parentViewGroup = (ViewGroup) ll.getParent();
// if (null != parentViewGroup) {
// parentViewGroup.removeView(ll);
// }
// }
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(ll != null) { return ll; }
return ll;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
I'm pretty sure it has to do with my SectionsPagerAdapter class or removing views, but I can't figure out how to fix it.
Help would be much appreciated.
Thanks so much!

Categories

Resources