I'm trying to add items at runtime to ListView placed on Tab.
But when I do so, I get an error. There are 3 tabs and I'm not using ListFragments, because I have different content in all tabs
my code below
SwipeTabFragment.java
public class SwipeTabFragment extends Fragment {
private String tab;
private int color;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
tab = bundle.getString("tab");
color = bundle.getInt("color");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.bookshelf, null);
TextView tv = (TextView) view.findViewById(R.id.textView);
tv.setText(tab);
view.setBackgroundResource(color);
return view;
}
}
TabPagerAdapter.java
public class TabPagerAdapter extends FragmentPagerAdapter {
public TabPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
Bundle bundle = new Bundle();
String tab = "";
int colorResId = 0;
SwipeTabFragment swipeTabFragment = new SwipeTabFragment();
switch (index) {
case 0:
tab = "BookShelf";
bundle.putString("tab",tab);
swipeTabFragment.setArguments(bundle);
return swipeTabFragment;
// break;
case 1:
tab = "Now Listening";
colorResId = R.color.color2;
BookFragment bookFragment = new BookFragment();
return bookFragment;
//break;
case 2:
tab = "Library";
colorResId = R.color.color3;
TabLibrary tabLibrary = new TabLibrary();
return tabLibrary;
break;
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
TabLibrary.java
public class TabLibrary extends Fragment {
final String LOG_TAG = "myLogs";
ListView lvLibList;
ImageButton btAddItem;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.library, parent, false);
ListView lvLibList = (ListView)v.findViewById(R.id.lvLibList);
ImageButton btn = (ImageButton)v.findViewById(R.id.btAddItem);
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText edit = (EditText)v.findViewById(R.id.eAddItem);
list.add(edit.getText().toString());
edit.setText("");
adapter.notifyDataSetChanged();
}
};
btn.setOnClickListener(listener);
lvLibList.setAdapter(adapter);
return v;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
#Gurusharan S is right, the problem is about the names of your variables. To avoid confusions I'd suggest to change your code to this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.library, parent, false); //Change the name from v to view
ListView lvLibList = (ListView)view.findViewById(R.id.lvLibList);
ImageButton btn = (ImageButton)view.findViewById(R.id.btAddItem);
EditText edit = (EditText)view.findViewById(R.id.eAddItem); //Initialize the EditText outside of the click method
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
list.add(edit.getText().toString());
edit.setText("");
adapter.notifyDataSetChanged();
}
};
btn.setOnClickListener(listener);
lvLibList.setAdapter(adapter);
return view;
}
And in the future I'd advice to give your variables more meaningful names, sometimes it takes you a little more coding but it is worth it.
Posting my comment as answer, as I'm pretty sure that is the issue:
The variable edit seems to be null. That is because when you call v.findViewById, you are actually calling it on the view that was clicked and NOT the fragment's view.
So you got two options:
Change the name of the fragment's view. eg. View v1 = inflater.inflate(R.layout.library, parent, false); and then change the line to v1.findViewById
Change the name of the argument of onClick. eg. public void onClick(View v1) {.
Hope that helps.
Related
I have a problem with the recyclerview in my app i have 2 fragments in the first one there is the recycler view which has to find the songs present in the device and put them in line in the second for now nothing. when I switch from one fragment to another the recycler view items double each time.
CODE:
HomeActvity
public class HomeActivity extends AppCompatActivity {
BottomNavigationView bottomNavigationView;
RecyclerView recyclerView;
TextView noMusicTextView;
HomeFragment homeFragment = new HomeFragment();
ProvaFragment provaFragment = new ProvaFragment();
#SuppressLint("MissingInflatedId")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
getSupportActionBar().hide();
noMusicTextView = findViewById(R.id.noSongs);
recyclerView = findViewById(R.id.recycler_view);
bottomNavigationView = findViewById(R.id.barra_navigazione);
getSupportFragmentManager().beginTransaction().replace(R.id.contenitore_frammenti, homeFragment).commit();
bottomNavigationView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
getSupportFragmentManager().beginTransaction().replace(R.id.contenitore_frammenti, homeFragment).commit();
return true;
case R.id.prova:
getSupportFragmentManager().beginTransaction().replace(R.id.contenitore_frammenti, provaFragment).commit();
return true;
}
return false;
}
});
}
}
HomeFragment
public class HomeFragment extends Fragment {
ArrayList<AudioModel> songsList = new ArrayList<>();
RecyclerView recyclerView;
TextView noMusicTextView;
#SuppressLint("MissingInflatedId")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView = view.findViewById(R.id.recycler_view);
noMusicTextView = view.findViewById(R.id.noSongs);
String[] projection = {
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DURATION,
};
String selection = MediaStore.Audio.Media.IS_MUSIC + " !=0";
Cursor cursor = getActivity().getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,projection,selection,null,null);
while(cursor.moveToNext()){
AudioModel songData = new AudioModel(cursor.getString(1), cursor.getString(0),cursor.getString(2));
if(new File(songData.getPath()).exists())
songsList.add(songData);
}
if(songsList.size() == 0){
noMusicTextView.setVisibility(View.VISIBLE);
}else{
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(new MusicListAdapter(songsList, getContext()));
}
return view;
}
}
MusicListAdapter
public class MusicListAdapter extends RecyclerView.Adapter<MusicListAdapter.ViewHolder>{
ArrayList<AudioModel> songsList;
Context context;
public MusicListAdapter(ArrayList<AudioModel> songsList, Context context) {
this.songsList = songsList;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.recycler_item,parent,false);
return new MusicListAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
AudioModel songData = songsList.get(position);
holder.titleTextView.setText(songData.getTitle());
}
#Override
public int getItemCount() {
return songsList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView titleTextView;
ImageView iconImageView;
public ViewHolder(View itemView) {
super(itemView);
titleTextView = itemView.findViewById(R.id.music_title_text);
iconImageView = itemView.findViewById(R.id.icon_view);
}
}
}
I have tryed to use songsList.clear(); but this don't work(Sorry for my english).
When switching fragments, existing fragments aren't deleted.
Also, songsList isn't initialized; onViewCreated() is called at this time, so it seems that the transition adds the item to the songsList.
In order to solve the problem, it seems that it is necessary to do a good comparison so that the same item as the previously saved item is not added, or to not add an item every time in onViewCreated.
I will be very grateful for the analysis of these lines of code, because I do not understand the relationship between them. Especially if I
I will change tags to 2 different tags, nothing changes in the application. In addition, if the condition if is removed, there are also no changes. In the comments I have a brief translation, I am still unable to understand these three lines.
Fragment fr = manager.findFragmentByTag("AddCity");
What role does this condition fulfill?
if (fr != null) {// if ???
manager.beginTransaction().remove(fr).commit();
}
And:
fr2.show(manager, "AddCity");
This is the whole code snippet
/*
I create a variable manager, and then I get a FragmentManager and assign it to the variable manager,
thanks to the variable manager, I can run actions on fragments
*/
FragmentManager manager = getSupportFragmentManager();
Fragment fr = manager.findFragmentByTag("AddCity");//I created fr variable and ???
Fragment1 fr1 = (Fragment1)
manager.findFragmentById(R.id.list); // I created fr1 variable and assigned fragment list to the variable fr1
if (view.equals(b1)) {
if (fr != null) {// if ???
manager.beginTransaction().remove(fr).commit();//Creates a new transaction to change fragments at runtime, removes an existing fragment, plans to commit the transaction.
}
Fragment2 fr2 = new Fragment2();//Created object Fragment2
fr2.show(manager, "AddCity");//Display the dialog box by adding the fragment to the given FragmentManager.
}
EDIT:
This is my MainActivity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button b1, b2;
static int itemSelected;
static boolean isSelected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = findViewById(R.id.button1);
b2 = findViewById(R.id.button2);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
}
#Override
public void onClick(View view) {
FragmentManager manager = getSupportFragmentManager();//
Fragment fr = manager.findFragmentByTag("addCity");
Fragment1 fr1 = (Fragment1)
getSupportFragmentManager().findFragmentById(R.id.list);
if (view.equals(b1)) {
if (fr != null) {
manager.beginTransaction().remove(fr).commit();
}
Fragment2 fr2 = new Fragment2();
fr2.show(manager, "");
}
if (view.equals(b2)) {
if (!fr1.cities.isEmpty()) {
if (isSelected) {
fr1.cities.remove(itemSelected);
fr1.adapter.notifyDataSetChanged();
itemSelected = 0;
isSelected = false;
fr1.getListView()
.setSelector(android.R.color.transparent);
} else {
Toast.makeText(this, "Select city to be deleted",
Toast.LENGTH_LONG).show();
}
}
}
}
}
Fragment1:
public class Fragment1 extends ListFragment {
ArrayList<String> cities = new ArrayList<>();
ArrayAdapter<String> adapter;
String name;
public Fragment1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_fragment1,
viewGroup, false);
adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_1, cities);
setListAdapter(adapter);
return view;
}
public void onListItemClick(ListView listView, View view,
int position, long id) {
MainActivity.itemSelected = position;
MainActivity.isSelected = true;
getListView().setSelector(android.R.color.holo_blue_dark);
}
}
Fragment2:
public class Fragment2 extends DialogFragment {
EditText et;
public Fragment2() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_fragment2, viewGroup, false);
}
public void onViewCreated(View view, Bundle savedInstanceState) {
et = view.findViewById(R.id.editText);
Button b = view.findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String country = et.getText().toString();
Fragment1 fr1 = (Fragment1)
getFragmentManager().findFragmentById(R.id.list);
if (!country.equals("")) {
fr1.cities.add(country);
fr1.adapter.notifyDataSetChanged();
}
getActivity().getSupportFragmentManager().beginTransaction()
.remove(Fragment2.this).commit();
}
});
}
}
You are adding another fragment in the same name. Can you try changing the name to something else and try?
Like
fr2.show(manager, "Add District");
so that you can find the difference.
Adding a fragment
Fragment fr2 = new Fragment();
FragmentManager manger = getSupportFragmentManager();
FragmentTransaction ft = manger.beginTransaction();
ft.add(R.id.placeHolder, fr2,tag);
ft.commitAllowingStateLoss();
if(fr2.isAdded()){
fr2.show(manager, "");
}
Before calling show, you have to add the fragment.
I try to set a Text in a Layout in a ViewPager, but if i do this there will be thrown a NullPointerException:
private ViewPager viewPager;
private ViewPagerAdapter viewPagerAdapter;
private LinearLayout dotsLayout;
private TextView[] dots;
private int[] layouts;
private Button btnNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_slider);
viewPager = (ViewPager) findViewById(R.id.view_pager);
dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
//btnSkip = (Button) findViewById(R.id.btn_skip);
btnNext = (Button) findViewById(R.id.btn_next);
layouts = new int[]{
R.layout.slide_header_bild_text,
R.layout.slide_header_bild_text_2,
R.layout.slide_01_03,
R.layout.slide_01_04,
R.layout.slide_01_05,
R.layout.slide_01_06,
R.layout.startquiz_layout};
//These two lines are the Problem
TextView t1 = (TextView) findViewByID(R.id.header_text);
t1.setText("Test")
// adding bottom dots
addBottomDots(0);
viewPagerAdapter = new ViewPagerAdapter();
viewPager.setAdapter(viewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
}
public void btnQuizStart(View v){
Intent intent = new Intent(this, Quiz.class);
this.startActivity(intent);
}
public void btnNextClick(View v)
{
// checking for last page
// if last page home screen will be launched
int current = getItem(1);
if (current < layouts.length) {
// move to next screen
viewPager.setCurrentItem(current);
} else {
launchHomeScreen();
}
}
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
addBottomDots(position);
// changing the next button text 'NEXT' / 'GOT IT'
if (position == layouts.length - 1) {
// last page. make button text to GOT IT
btnNext.setText(getString(R.string.start));
} else {
// still pages are left
btnNext.setText(getString(R.string.next));
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
private void addBottomDots(int currentPage) {
dots = new TextView[layouts.length];
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(getResources().getColor(R.color.inactive_dots));
dotsLayout.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(getResources().getColor(R.color.active_dots));
}
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
private void launchHomeScreen() {
startActivity(new Intent(this, MainActivity.class));
finish();
}
public class ViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public ViewPagerAdapter() {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(layouts[position], container, false);
container.addView(view);
return view;
}
#Override
public int getCount() {
return layouts.length;
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
I've got the ViewPager which contains seven Pages.
I think the Layout wont be found, so the TextView is Null. I also read that I have to configure the instantiateItem method and to add there the TextView and the setter. Anybody can help?
findViewByID(R.layout.header_text)
TaxtView can't be a layout.
oh this was also a failure but not which I searched for. I had the problem with the viewpager that i didn't got the layout and so the elements of the layout was null. I fixed the instantiateItem Method so any layout will be initiated specific:
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View one = layoutInflater.inflate(R.layout.slide_type_a, container, false);
WebView header_1_a = (WebView) one.findViewById(R.id.header_slide_type_a_1);
loadHTLMContentHeader(getString(R.string.Historie1_header),header_1_a);
ImageView image_1_a = (ImageView) one.findViewById(R.id.image_slide_type_a_1);
image_1_a.setImageResource(R.drawable.picture_kap01_01);
WebView text_1_a = (WebView) one.findViewById(R.id.text_slide_type_a_1);
loadHTLMContentText(getString(R.string.Historie1), text_1_a);
View two = layoutInflater.inflate(R.layout.slide_type_a, container, false);
View three = layoutInflater.inflate(R.layout.slide_type_a, container, false);
View four = layoutInflater.inflate(R.layout.slide_type_b, container, false);
View five = layoutInflater.inflate(R.layout.slide_type_b, container, false);
View six = layoutInflater.inflate(R.layout.slide_type_b, container, false);
View seven = layoutInflater.inflate(R.layout.slide_type_b, container, false);
View eight = layoutInflater.inflate(R.layout.startquiz_layout, container, false);
View viewarr[] = {one, two, three, four, five, six, seven, eight};
container.addView(viewarr[position]);
return viewarr[position];
}
So after initiate the layout, i can get the xml element and change the content of it.
I would change fragment in the viewpager using a button in every fragment. So in the fragment in position 0 i have a button and onClick i'll change in second fragment (position 1) and so on. Actually i'm using this code in the fragment at position 0:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.open_welcome_fragment_layout, container,
false);
final WelcomeViewPager pagerV = new WelcomeViewPager();
Button nextBtnOpen = (Button)view.findViewById(R.id.button_next_open);
nextBtnOpen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((WelcomeViewPager)getActivity()).setCurrentItem(1, true);
}
});
return view;
}
position 1:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.firstwelcomefrg, container, false);
final WelcomeViewPager pagerV = new WelcomeViewPager();
Button nextBtn = (Button)view.findViewById(R.id.button_next_one);
nextBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((WelcomeViewPager)getActivity()).setCurrentItem(2, true);
}
});
return view;
}
position 2:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.secondwelcomefrg, container,
false);
final WelcomeViewPager pagerV = new WelcomeViewPager();
Button nextBtnTwo = (Button)view.findViewById(R.id.button_next_two);
nextBtnTwo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((WelcomeViewPager)getActivity()).setCurrentItem(3, true);
}
});
return view;
}
and in my ViewPager Activity i created this method:
public void setCurrentItem (int item, boolean smoothScroll) {
mViewPager.setCurrentItem(item, smoothScroll);
}
unfortunatelly not works. I can change from first to second fragment but every fragment returns to second.. Seems that the only one position accepted is the first one. In this case:
((WelcomeViewPager)getActivity()).setCurrentItem(1, true);
why this behaviour?
I think what you are trying to do is to have tabs and each tab to help switch between views. You should use actionBar tabs for this, not buttons.
This should help. It is a pretty detailed tutorial.
Do you want Button ? I use for similary problem solving with listener. Example of code below. Maybe help.
PagerActivity.java
import com.example.zzztest2.MyPagerAdapter.OnPagerItemSelected;
public class PagerActivity extends Activity implements OnPagerItemSelected {
ViewPager viewPager;
ArrayList<Bitmap> bitmapArray=null;
ArrayList<String> textArray=null;
ArrayList<String> urlArray=null;
int pagexi;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reklamapager);
viewPager = (ViewPager) findViewById(R.id.view_pager);
//setting adapter
new readAsync().execute();
}//end oncreate
//switch page
public void pagerItemSelected(int newposition) {
viewPager.setCurrentItem(newposition);
}
Setting my adapter in onpostexecute Async
protected void onPostExecute(String file_url) {
MyPagerAdapter adapter = new MyPagerAdapter(PagerActivity.this, textArray, urlArray, bitmapArray, PagerActivity.this );
viewPager.setAdapter(adapter);
//start position
int pagexi = 2;
viewPager.setCurrentItem(pagexi);
}
MyPagerAdapte.java
public class MyPagerAdapter extends PagerAdapter {
Context context;
OnPagerItemSelected mListener;
ArrayList<String> textArray;
ArrayList<String> urlArray;
ArrayList<Bitmap> bitmapArray;
ImageView imageView;
TextView textreklama1;
Button btnSwitchPage;
public Activity activity;
String firmax;
String adresarx;
MyPagerAdapter(Context context, ArrayList<String> textArray, ArrayList<String> urlArray, ArrayList<Bitmap> bitmapArray, OnPagerItemSelected listener){
this.context=context;
this.textArray=textArray;
this.urlArray=urlArray;
this.bitmapArray=bitmapArray;
this.mListener = listener;
}
#Override
public int getCount() {
return textArray.size();
}
public Object instantiateItem(ViewGroup collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.reklamator_new, null);
String indexx = textArray.get(position).toString();
String delims2 = "[;]+";
String[] riadokxxx = indexx.split(delims2);
String ucex = riadokxxx[0].trim();
String dokx = riadokxxx[1].trim();
EditText inputUce = (EditText) view.findViewById(R.id.inputUce);
inputUce.setText(ucex);
EditText inputDok = (EditText) view.findViewById(R.id.inputDok);
inputDok.setText(dokx);
btnSwitchPage = (Button) view.findViewById(R.id.btnSwitchPage);
btnSwitchPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//here set new position
int xxx=1;
mListener.pagerItemSelected(xxx);
}
});
((ViewGroup) collection).addView(view, 0);
return view;
}
#Override
public void destroyItem(ViewGroup arg0, int arg1, Object arg2) {
((ViewGroup) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
//new position
public interface OnPagerItemSelected {
void pagerItemSelected(int xxx);
}
}
I've make it more simple and updated it based on the answers in my previous post: Adding Assigned Values in Spinner NullPointerException
I have a MainAcitivty that uses a ViewPager. I have 2 Fragments in my MainActivity (FragA and FragB)
In my FragA I have a spinner. While in FragB, I have a TextView and a Button.
Now what am I trying to do is, when I select "Hello" in my spinner, my int a will have a value of 5. And when I click the Button, 5 will display in the TextView.
Here's my code:
FragA
public class FragA extends Fragment {
Spinner spinner1;
String s1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fraga, container, false);
spinner1 = (Spinner) view.findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter_a = ArrayAdapter.createFromResource(getActivity(), R.array.spinner1,android.R.layout.simple_spinner_item );
spinner1.setAdapter(adapter_a);
s1 = spinner1.getSelectedItem().toString();
return view;
}
public int getInt() {
int a = 0;
if(s1.equals("Hello")) {
a = 5;
}
return a;
}
}
MainActivity
public class MainActivity extends FragmentActivity {
ViewPager viewPager = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.pager);
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new MyAdapter(fragmentManager));
}
public class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter (FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = null;
if (i == 0)
{
fragment = new FragA();
}
if (i == 1)
{
fragment = new FragB();
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
}
public String get() {
FragA FragA = new FragA();
return Integer.toString(FragA.getInt());
}
}
FragB
public class FragB extends Fragment{
TextView textView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragb, container, false);
textView = (TextView) view.findViewById(R.id.textview);
Button button = (Button) view.findViewById(R.id.button);
button.setOnClickListener(Click);
return view;
}
OnClickListener Click = new OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(((MainActivity)getActivity()).get());
}
};
}
By the way, I have no problem passing the value of a from FragA to FragB when this is my code:
public int getInt() {
int a = 5;
return a;
}
But, it doesn't involve my spinner and that's not I want to do.
Here is a simple way to communicate between fragments.
In MainActivity, keep static instances of the fragments.
public static FragA fragmentA;
public static FragB fragmentB;
Now if you want to access FragB from FragA, write something similar:
((MainActivity) getActivity()).fragmentB.setSomething();
And Here is a better/proper way to communicate between fragments:
http://developer.android.com/training/basics/fragments/communicating.html