I want to set the text of some EditTexts after clicking on an item of a list.
The activity:
- CadPersonActivity
And three fragments, each one having fields:
- FragmentPersonId
- FragmentPersonAddress
- FragmentPersonPhones
However those EditTexts insist on not showing what I expect.
There's no error, but blank fields.
I hope someone can help me.
Thanks in advance.
THE ACTIVITY
CadPersonActivity recover the Id in Bundle extras:
public class CadPersonActivity extends FragmentActivity implements TabListener {
private ActionBar actionBar;
private ViewPager viewPager;
private PersonPageAdapter pageAdapter;
private Person person;
private PersonDAO bd;
private Bundle extras;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cad_person);
extras = getIntent().getExtras();
actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
pageAdapter = new PersonPageAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(pageAdapter);
viewPager.setPageTransformer(true, new ZoomOutPageTransformer());
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
});
actionBar.addTab(actionBar.newTab().setText(getString(R.string.tab_id)).setTabListener(this));
actionBar.addTab(actionBar.newTab().setText(getString(R.string.tab_address)).setTabListener(this));
actionBar.addTab(actionBar.newTab().setText(getString(R.string.tab_phones)).setTabListener(this));
if (extras.getInt("id") > 0) {
bd = new PersonDAO(getApplicationContext());
person = bd.getPerson(extras.getInt("id"));
callSetFields();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (bd != null)
bd.close();
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
private void callSetFields() {
try {
FragmentPersonId fragId = (FragmentPersonId) getSupportFragmentManager().findFragmentById(R.id.fragment_id);
fragId.setFields(person);
FragmentPersonAddress fragEndereco = (FragmentPersonAddress) getSupportFragmentManager().findFragmentById(R.id.fragment_endereco);
fragEndereco.setFields(person);
FragmentPersonPhones fragPhones = (FragmentPersonPhones) getSupportFragmentManager().findFragmentById(R.id.fragment_phones);
fragPhones.setFields(person);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "An error occurred while trying to open the record.", Toast.LENGTH_SHORT).show();
}
}
}
CallSetFields is called when a record is clicked and its Id is passed to CadPersonActivity.
The activity_cad_person.xml:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/fragment_id"
android:name="com.fragment.FragmentPersonId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
tools:layout="#layout/fragment_id" />
<fragment
android:id="#+id/fragment_address"
android:name="com.fragment.FragmentPersonAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
tools:layout="#layout/fragment_address" />
<fragment
android:id="#+id/fragment_phones"
android:name="com.fragment.FragmentPersonPhones"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
tools:layout="#layout/fragment_phones" />
</android.support.v4.view.ViewPager>
THE FRAGMENTS:
And each fragment have a code like this:
public class FragmentPersonId extends Fragment {
private EditText edtName;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_id, container,
false);
return view;
}
public void setFields(Pessoa pessoa) {
try {
edtName = (EditText) getView().findViewById(R.id.edtName);
edtName.setText(person.getName());
} catch (Exception e) {
Toast.makeText(getActivity().getApplicationContext(), "Error while setting fields.", Toast.LENGTH_SHORT).show();
}
}
}
Well, after some days searching and trying, I have this
Declare the class Person in CadPersonActivity as public static;
public static Person person;
Now, instantiate these EditTexts and call person.getName directly in onCreateView;
edtName = (EditText) view.findViewById(R.id.edtName);
edtName.setText(CadPersonActivity.person.getName());
I can't see this as a good solution, but it's the best I could find.
Related
I'm creating tab view using tablayout and viewpager. I use one fragment for each tab. And in my MainActivity, I'm getting some values from a device through bluetooth. The values are received as a single string, and I split it and sets it to corresponding tabs. But I'm getting a NullPointerException when I try to call the setText method for the textview in fragment from my activity.
Can anybody show me how to update the textviews of each of the fragments from my MainActivity?? Like, if i select the temperature tab, the textview in the temperature fragment should be updated with the value from MainActivity. Please Help
Activity
public class MainActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener {
Handler bluetoothIn;
private static TextView tmpF, humF, CoF;
String tempGL, HumGL, coGL, devname;
double dblTemp, dblCo;
final int handlerState = 0; // used to identify handler message
private BluetoothAdapter btAdapter = null;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frag_home);
tmpF = (TextView)findViewById(R.id.txt_temp_val);
humF = (TextView)findViewById(R.id.txt_hum_val);
co = (TextView)findViewById(R.id.txt_co_val);
//Adding toolbar to the activity
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing the tablayout
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.pager);
//Adding the tabs using addTab() method
tabLayout.addTab(tabLayout.newTab().setText("Temperature"));
tabLayout.addTab(tabLayout.newTab().setText("Humidity"));
tabLayout.addTab(tabLayout.newTab().setText("CO"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//Creating our pager adapter
Pager adapter = new Pager(getSupportFragmentManager(), tabLayout.getTabCount());
//Adding adapter to pager
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
//Adding onTabSelectedListener to swipe views
tabLayout.setOnTabSelectedListener(this);
bluetoothIn=new Handler() {
String readMessage;
String[] values = new String[]{""};
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) {
readMessage = (String) msg.obj;
values = readMessage.split("#");
for (int j = 0; j < values.length; j++) {
int rem = j % 3;
if (rem == 0) {
tmpF.setText(values[j] + " C");
tempGL = String.valueOf(values[j]);
try {
dblTemp = Double.parseDouble(tempGL);
} catch (NumberFormatException e) {
e.printStackTrace();
}
} else if (rem == 1) {
CoF.setText(values[j] + " ppm");
coGL = values[j];
try {
dblCo = Double.parseDouble(coGL);
} catch (NumberFormatException e) {
e.printStackTrace();
}
} else if (rem == 2) {
humF.setText(values[j] + " %");
HumGL = values[j];
}
}
}
}
};
btAdapter=BluetoothAdapter.getDefaultAdapter(); // get Bluetooth
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
// mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
}
Tab1
public class OneFragment extends Fragment {
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_one, container, false);
return view;
}
}
fragment_one.xml
<RelativeLayout 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"
tools:context="shinil.tablayout.OneFragment"
android:id="#+id/rltnvnv">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Temperature"
android:textSize="40dp"
android:textStyle="bold"
android:id="#+id/txt_temp_val"
android:layout_centerInParent="true"/>
</RelativeLayout>
Logcat
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.view.ViewPager.setAdapter(android.support.v4.view.PagerAdapter)' on a null object reference at shinil.airopure.MainActivity.onCreate(MainActivity.java:194)
frag_home.xml
<LinearLayout
android:id="#+id/main_layout"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
Hi i'm not sure if i understand your problem correctly but let me try to help.
I assume your ViewPager adapter extends from FragmentStatePagerAdapter
First in your Pager adapter define a SparseArray for your fragments like below:
SparseArray<Fragment> myPagerFragments= new SparseArray<>();
In your adapter's instantiateItem method add your fragment to your sparsearray.
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
myPagerFragments.put(position, fragment);
return fragment;
}
And in your destroyItem method remove your fragment from your sparsearray.
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
myPagerFragments.remove(position);
super.destroyItem(container, position, object);
}
Add a method to your adpater which returns your pager fragment likew below:
public Fragment getRegisteredFragment(int position) {
return myPagerFragments.get(position);
}
In your fragments define a public method which changes your TextView's text likew below:
public void setText(String text){
myTextView.setText(text);
}
In your activity define your adapter and add an onPageChangeListener to your ViewPager like below:
MyPagerAdapter mAdapter = new MyPagerAdapter(context,items);
myViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Fragment myPagerFragment = mAdapter.getRegisteredFragment(position);
if(fragment != null){
((YourFragment)fragment).setText("Hello World!");
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
I hope this'll help you. Good luck.
This is MyTabActivity.java class
public class MyTabActivity extends FragmentActivity {
ViewPager Tab;
TabPagerAdapter TabAdapter;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_layout);
TabAdapter = new TabPagerAdapter(getSupportFragmentManager());
Tab = (ViewPager)findViewById(R.id.pager);
Tab.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar = getActionBar();
actionBar.setSelectedNavigationItem(position); }
});
Tab.setAdapter(TabAdapter);
actionBar = getActionBar();
//Enable Tabs on Action Bar
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.TabListener tabListener = new ActionBar.TabListener(){
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
Toast.makeText(getBaseContext(), "Tab ReSelected: " + tab.getPosition(), Toast.LENGTH_SHORT).show();
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
Tab.setCurrentItem(tab.getPosition());
Toast.makeText(getBaseContext(), "Tab Selected: " + tab.getPosition(), Toast.LENGTH_SHORT).show();
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
Toast.makeText(getBaseContext(), "Tab UnSelected: " + tab.getPosition(), Toast.LENGTH_SHORT).show();
}};
//Add New Tab
actionBar.addTab(actionBar.newTab().setText("Tab1").setTabListener(tabListener));
actionBar.addTab(actionBar.newTab().setText("Tab2").setTabListener(tabListener));
}
}
This is TabPagerAdapter.java
public class TabPagerAdapter extends FragmentStatePagerAdapter {
public TabPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
return new Tab1Activity();
case 1:
return new Tab2Activity();
}
return null;
}
#Override
public int getCount() {
//No of Tabs
return 2;
}
}
public class Tab1Activity extends Fragment {
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
/// code to display LIstView
.
.
//here i m trying to invoke other tab on click of list item...this where i stuck
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adptr, View view, int pos,
long id) {
/// this code here is not working for me
Tab2Activity myDetailFragment = new Tab2Activity ();
Bundle bundle = new Bundle();
bundle.putString("KEY_DETAIL", "Hi");
myDetailFragment.setArguments(bundle);
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.attach(myDetailFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}});
return monthlyView;
}
}
This is Tab2Activity.java
public class Tab2Activity extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View dailyView = inflater.inflate(R.layout.activity_mian, container, false);
// displaying list item based on the input from tab1
return dailyView;
}
}
This is activity_main.xml
<RelativeLayout 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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ListView
android:id="#+id/list_View1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ListView>
</RelativeLayout>
This is pager.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- The main content view starts -->
<LinearLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
Now my question is, i am displaying a list of item using listview in tab1
and i want to invoke tab2 when user click on the list item of tab1
and display some data on tab2 by sending some data from tab1 to tab2.
I an mew to android, please guide me with proper solutions. Thanks :)
Use viewPager.setCurrentItem(position, true); to switch between tabs.
Then, use this to get the current fragment.
Then you call a public method of that fragment that you create to do whatever you want.
I created a Tab Layout with Swipeable Views using this tutorial. I'm trying to pass a string from Activity to Fragment. I read about fragment communication and couple other topics on stackoverflow but still i get null pointer exception. Here's my code:
MainActivity.java
public class MainActivity extends FragmentActivity {
private static final int REQUEST_CODE_EMAIL = 1;
String password, email;
ViewPager viewPager;
TabsPagerAdapter tabsPagerAdapter;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabsPagerAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar = getActionBar();
actionBar.setSelectedNavigationItem(position);
}
});
viewPager.setAdapter(tabsPagerAdapter);
actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabReselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
// TODO Auto-generated method stub
}
};
actionBar.addTab(actionBar.newTab().setText("Głowna").setTag("main").setTabListener(tabListener));
actionBar.addTab(actionBar.newTab().setText("Rachunki").setTag("bills").setTabListener(tabListener));
Bundle bundle=new Bundle();
bundle.putString("email", "emasiofnasdbjk");
EnterExitFragment enterExitFragment = new EnterExitFragment();
android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.pager, enterExitFragment);
transaction.addToBackStack(null);
transaction.commit();
}
activity_main.xml
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
TabsPagerAdapter.java
public class TabsPagerAdapter extends FragmentStatePagerAdapter {
public TabsPagerAdapter(FragmentManager fragmentManager){
super(fragmentManager);
}
#Override
public Fragment getItem(int i) {
switch (i){
case 0:
return new EnterExitFragment();
case 1:
return new BillsFragment();
}
return null;
}
#Override
public int getCount() {
return 2;
}
}
EnterExitFragment.java
public class EnterExitFragment extends Fragment{
TextView tvFloor1, tvFloor2, tvEmail;
Button btnSend;
Integer floorId, segmentId, spaceId, ticketId;
String floorName, segmentName, spaceName;
String email;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_enter_exit, container, false);
tvEmail = ((TextView)rootView.findViewById(R.id.textEmail));
tvFloor1 = ((TextView)rootView.findViewById(R.id.textFloor1));
tvFloor2 = ((TextView)rootView.findViewById(R.id.textFloor2));
new FloorFreeSpaces(EnterExitFragment.this).execute();
btnSend = ((Button)rootView.findViewById(R.id.btnSend));
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Floor(EnterExitFragment.this).execute();
email = getArguments().getString("email"); //line 55
tvEmail.setText(email);
}
});
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
activity_enter_exit.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textFloor1"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textFloor2"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="354dp"
android:layout_height="93dp"
android:text="Email:"
android:id="#+id/textEmail"
android:layout_gravity="center_horizontal|bottom" />
<Button
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="SEND"
android:id="#+id/btnSend"
android:layout_gravity="center_horizontal|bottom" />
</LinearLayout>
error log
java.lang.NullPointerException
at com.carpark.EnterExitFragment$1.onClick(EnterExitFragment.java:55)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17722)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5303)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
at dalvik.system.NativeStart.main(Native Method)
Has anyone solution for my problem? :)
EDIT: My suggestion is to make the following constructor which takes Bundle object as an argument:
public EnterExitFragment(Bundle bundle) {
super();
setArguments(bundle);
}
and call that constructor with bundle object as the argument instead of the default one in your program. That way you're sure to add the bundle before you attach it to your Activity.
Additionally, if that doesn't work, add a Bundle attribute to your EEF class, initialize it within your constructor and refer to it rather than getArguments() method:
public class EnterExitFragment extends Fragment{
TextView tvFloor1, tvFloor2, tvEmail;
Button btnSend;
Integer floorId, segmentId, spaceId, ticketId;
String floorName, segmentName, spaceName;
String email;
Bundle args;
public EnterExitFragment(Bundle bundle) {
super();
args = bundle;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_enter_exit, container, false);
tvEmail = ((TextView)rootView.findViewById(R.id.textEmail));
tvFloor1 = ((TextView)rootView.findViewById(R.id.textFloor1));
tvFloor2 = ((TextView)rootView.findViewById(R.id.textFloor2));
new FloorFreeSpaces(EnterExitFragment.this).execute();
btnSend = ((Button)rootView.findViewById(R.id.btnSend));
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Floor(EnterExitFragment.this).execute();
email = args.getString("email"); //line 55
tvEmail.setText(email);
}
});
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
I do not see that you set your argument to fragment. If you did, but you forgotten to write please inform me...
Bundle bundle=new Bundle();
bundle.putString("email", "emasiofnasdbjk");
EnterExitFragment enterExitFragment = new EnterExitFragment();
enterExitFragment.setArguments(bundle); // This line is needed...
android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.pager, enterExitFragment);
transaction.addToBackStack(null);
transaction.commit();
I try to start a tab, which can be swiped. It works fine! But if I try to implement Google Maps, then it works unit I switch the tab and go to the map back. I get these kind of Error:
E/AndroidRuntime(25324): FATAL EXCEPTION: main
E/AndroidRuntime(25324): android.view.InflateException: Binary XML file line #21: Error inflating class fragment
I searched many times in google and couldn't find a solution.
This is the MainActivity class Code:
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;
GoogleMapOptions nMap;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three primary sections
// of the app.
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
// Set up the action bar.
final ActionBar actionBar = getActionBar();
// Specify that the Home/Up button should not be enabled, since there is no hierarchical
// parent.
actionBar.setHomeButtonEnabled(false);
// Specify that we will be displaying tabs in the action bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set up the ViewPager, attaching the adapter and setting up a listener for when the
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between different app sections, select the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if we have a reference to the
// Tab.
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mAppSectionsPagerAdapter.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
// listener for when this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mAppSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#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 onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
// The first section of the app is the most interesting -- it offers
// a launchpad into the other demonstrations in this example application.
Fragment f1 = new LayersDemoActivity2();
return f1;
default:
// The other sections of the app are dummy placeholders.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
fragment.setArguments(args);
return fragment;
}
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch(position){
case 0: return "Timeline";
case 1: return "Chat";
case 2: return "Fh";
case 3: return "Mehr";
default: return "Section " + (position + 1);
}
}
}
/**
* A dummy fragment representing a section of the app, but that simply displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_dummy, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1)).setText(
getString(R.string.dummy_section_text, args.getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
Tab 1 calls this Fragment
public class LayersDemoActivity2 extends Fragment implements OnItemSelectedListener {
private GoogleMap mMap;
private CheckBox mTrafficCheckbox;
private CheckBox mMyLocationCheckbox;
//neu hinzugekommen
private LocationClient locationclient;
private String TAG = this.getClass().getSimpleName();
//neu hinzugekommen
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.layers_demo, container, false);
// Demonstration of a collection-browsing activity.
rootView.findViewById(R.id.traffic)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateTraffic();
}
});
// Demonstration of a collection-browsing activity.
rootView.findViewById(R.id.my_location)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateMyLocation();
}
});
// Demonstration of a collection-browsing activity.
rootView.findViewById(R.id.button1)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!checkReady()) {
return;
}
try{
LatLng hier = new LatLng(mMap.getMyLocation().getLatitude(), mMap.getMyLocation().getLongitude());
Marker setzen = mMap.addMarker(new MarkerOptions().position(hier).title("Here I am!"));
}catch(Exception e){
}
}
});
return rootView;
}
#Override
public void onStart() {
super.onStart();
Spinner spinner = (Spinner) getView().findViewById(R.id.layers_spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
getView().getContext(), R.array.layers_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
mTrafficCheckbox = (CheckBox) getView().findViewById(R.id.traffic);
mMyLocationCheckbox = (CheckBox) getView().findViewById(R.id.my_location);
setUpMapIfNeeded();
}
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
if (mMap != null) {
updateTraffic();
updateMyLocation();
}
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
}
}
private boolean checkReady() {
if (mMap == null) {
//getView().Toast.makeText(this, R.string.map_not_ready, Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
private void updateTraffic() {
if (!checkReady()) {
return;
}
mMap.setTrafficEnabled(mTrafficCheckbox.isChecked());
}
private void updateMyLocation() {
if (!checkReady()) {
return;
}
mMap.setMyLocationEnabled(mMyLocationCheckbox.isChecked());
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
setLayer((String) parent.getItemAtPosition(position));
}
private void setLayer(String layerName) {
if (!checkReady()) {
return;
}
if (layerName.equals(getString(R.string.normal))) {
mMap.setMapType(MAP_TYPE_NORMAL);
} else if (layerName.equals(getString(R.string.hybrid))) {
mMap.setMapType(MAP_TYPE_HYBRID);
} else if (layerName.equals(getString(R.string.satellite))) {
mMap.setMapType(MAP_TYPE_SATELLITE);
} else if (layerName.equals(getString(R.string.terrain))) {
mMap.setMapType(MAP_TYPE_TERRAIN);
} else {
Log.i("LDA", "Error setting layer with name " + layerName);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
}
last but not least, this is layers_demo.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
<!-- A set of test checkboxes. -->
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignTop="#id/map"
android:background="#D000"
android:orientation="vertical"
android:padding="6dp" >
<Spinner
android:id="#+id/layers_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<CheckBox
android:id="#+id/traffic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onTrafficToggled"
android:text="#string/traffic" />
<CheckBox
android:id="#+id/my_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onMyLocationToggled"
android:text="#string/my_location" />
</LinearLayout>
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:onClick="tagOnMyLocation"
android:text="#string/tag_me" />
and the activity_main.xml layout
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
I guess it has something to do with fragment, but I dont know how and I dont know why. Please help. :(
Just paste this method after oncreatview method
#Override
public void onDestroyView() {
Fragment f = (Fragment) getFragmentManager().findFragmentById(R.id.map);
if (f != null) {
getFragmentManager().beginTransaction().remove(f).commit();
}
super.onDestroyView();
}
I am trying to get a fragment with three tabs displayed using ViewPager. Initially I used to instantiate the fragment from the Activity using FragmentMgr, this worked fine. When I converted this navigation using ViewPager, this Fragment is no longer displayed.
MainActivity.java
When I initiate Fragment like this, it gets displayed. eg:
LaunchListFragment fragment = new LaunchListFragment();
fragment.newInstance(LIST_TYPE);
getSupportFragmentManager().beginTransaction()
.add(R.id.item_detail_container,
fragment).commit();
I tried this change above code to make use of ViewPager as follows:
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(new LaunchPageAdapter(getSupportFragmentManager(),LIST_TYPE));
mViewPager.setCurrentItem(0);
where LaunchPageAdapter calls LaunchListFragment.
LaunchPageAdapter.java
public class LaunchPageAdapter extends FragmentPagerAdapter {
private static String select="";
public LaunchPageAdapter(FragmentManager fm, String type) {
super(fm);
select=type;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return LaunchListFragment.newInstance(select);
case 1:
return AddTeamFragment.newInstance();
}
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 2;
}
Here is LaunchListFragment.java
public class LaunchListFragment extends ListFragment implements ActionBar.TabListener {
public static String LIST_TYPE = "invalid";
GenericListData g_data[] = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View result = inflater.inflate(R.layout.fragment_launch_list,
container, false);
setActionTabs();
setList();
return (result);
}
public static Fragment newInstance(String type) {
Fragment frag = new LaunchListFragment();
Bundle args = new Bundle();
LIST_TYPE=type;
args.putString(LIST_TYPE, type);
frag.setArguments(args);
return (frag);
}
This is main.xml layout used by MainActivity
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools= "match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:baselineAligned="false"
android:divider="?android:attr/dividerHorizontal"
android:orientation="horizontal"
android:showDividers="middle"
tools:context=".MainActivity" >
<fragment
android:id="#+id/item_list"
android:name="com.teammanager.ItemListFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
tools:layout="#android:layout/list_content" />
<FrameLayout
android:id="#+id/item_detail_container"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</FrameLayout>
fragment_launch_list.xml used by LaunchListFragment
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:drawSelectorOnTop="false" >
</ListView>
<TextView
android:id="#+id/itemName"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:gravity="center_vertical"
android:textColor="#000000"
android:textSize="22dp"
android:textStyle="bold" />
When I debug this, I can see LaunchListFragment is getting instantiated, onCreate and onCreate View is called, it just won't get displayed. :(
Can anyone here let me know if I am missing anything here in my ViewPager implementation?
Update
When I called LaunchListFragment without using Viewpager, I set the content view first and passed R.id.item_detail_container which is the id of the FrameLayout where I want the fragment to be displayed. Please refer to main.xml earlier
setContentView(R.layout.main.xml);
LaunchListFragment fragment = new LaunchListFragment();
fragment.newInstance(LIST_TYPE);
getSupportFragmentManager().beginTransaction()
.add(R.id.item_detail_container,
fragment).commit();
When I changed this to use ViewPager, I am not sure where I'm directing the Fragment to be displayed. In my fragment onView I'm inflating fragment_launch_list and returning the View. But how will the view pager know where to set the fragment view. Is it inside the id pager?
I'm an absolute beginner, I apologize if all these are naive questions.
Cheers.
The question description is perfectly suitable to the problem I just had. I know the question is old but may this help other who face same. #Geoplex have not shown code of LaunchPageAdapter class. So I'm not sure if this solves his problem or not. But for me that worked.
In my PagerAdapter, the
public boolean isViewFromObject(View view, Object object) was overridden. I removed that method and allowed superClass to handle it. That started giving my expected result.
This is useful for you,
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragments=null;
private FragmentManager fragmentManager=null;
public ViewPagerAdapter(FragmentManager fragmentManager,List<Fragment> fragments) {
super(fragmentManager);
this.fragments=fragments;
this.fragmentManager=fragmentManager;
}
#Override
public Fragment getItem(int position) {
fragmentManager.beginTransaction().commitAllowingStateLoss();
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object)
{
super.setPrimaryItem(container,0,fragments.get(0));
}
#Override
public void notifyDataSetChanged()
{
super.notifyDataSetChanged();
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
fragmentManager.executePendingTransactions();
fragmentManager.saveFragmentInstanceState(fragments.get(position));
}
public void replaceItem(int position,Fragment fragment)
{
fragments.set(position, fragment);
this.notifyDataSetChanged();
}
}
MainActivity.java
public class MainActivity extends FragmentActivity implements OnPageChangeListener,TabListener
{
private android.support.v4.view.ViewPager mViewPager=null;
private ViewPagerAdapter mPagerAdapter=null;
private ActionBar action=null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
initilizeViewPager();
action=getActionBar();
action.setDisplayShowHomeEnabled(false);
action.setDisplayShowTitleEnabled(false);
action.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}
public void initilizeViewPager()
{
mViewPager=(android.support.v4.view.ViewPager)findViewById(R.id.viewPager);
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(LaunchListFragment.newInstance(select));
fragments.add(AddTeamFragment.newInstance());
fragments.add(thirdFragment.newInstance());
viewPagerAdapter=new ViewPagerAdapter();
mViewPager.setAdapter(viewPagerAdapter(getSupportFragmentManager(),fragments));
new setAdapterTask().execute();
mViewPager.setOnPageChangeListener(this);
}
private class setAdapterTask extends AsyncTask<Void,Void,Void>
{
protected Void doInBackground(Void... params)
{
return null;
}
#Override
protected void onPostExecute(Void result)
{
mViewPager.setAdapter(mPagerAdapter);
Tab first=action.newTab().setTag("first").setText("First").setTabListener(MainActivity.this);
Tab second=action.newTab().setTag("second").setText("Second").setTabListener(MainActivity.this);
Tab third=action.newTab().setTag("third").setText("Third").setTabListener(MainActivity.this);
action.addTab(first);
action.addTab(second);
action.addTab(third);
}
}
}
public void onPageScrollStateChanged(int arg0)
{}
public void onPageScrolled(int arg0, float arg1, int arg2)
{}
public void onPageSelected(int position)
{
getActionBar().setSelectedNavigationItem(position);
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {}
}
main_layout.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_below="#android:id/tabs"
android:layout_height="fill_parent"/>
</RelativeLayout>