TextView.setText() in fragment crashes app - android

I am trying to change TextView content on Sensor change but after calling TextView.setText("foo"); app crashes as if the TextView variable was null. I set up the TextView variable in onCreateView. Here is the code:
public class fragment1 extends Fragment implements SensorEventListener
{
private SensorManager mSrMgr = null;
private Sensor mLight;
private TextView page1;
protected View mView;
public fragment1()
{
// Required empty public constructor
}
public void onCreate(Bundle savedInstance)
{
super.onCreate(savedInstance);
mSrMgr = (SensorManager) getActivity().getSystemService(SENSOR_SERVICE);
mLight = mSrMgr.getDefaultSensor(Sensor.TYPE_LIGHT);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
page1 = container.findViewById(R.id.page1);
View view = inflater.inflate(R.layout.fragment_fragment1, container, false);
this.mView = view;
return inflater.inflate(R.layout.fragment_fragment1, container, false);
}
public void onPause()
{
super.onPause();
this.unregister();
}
public void onResume()
{
super.onResume();
this.registerSensorListiner();
}
private void registerSensorListiner()
{
mSrMgr.registerListener(this, mLight, SensorManager.SENSOR_DELAY_NORMAL);
}
private void unregister()
{
mSrMgr.unregisterListener(this);
}
#Override
public void onSensorChanged(SensorEvent event)
{
Toast.makeText(getContext(),String.valueOf(event.values[0]),Toast.LENGTH_SHORT).show();
page1.setText("elo"); //here is the crashing part
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
}

First, inflate the layout
View view = inflater.inflate(R.layout.fragment_fragment1, container, false);
this.mView = view;
page1 = view.findViewById(R.id.page1);
return view, false);
use view object to call findViewById method

Use this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_fragment1, container, false);
this.mView = view;
page1 = view.findViewById(R.id.page1);
return view;
}
Instead of this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
page1 = container.findViewById(R.id.page1);
View view = inflater.inflate(R.layout.fragment_fragment1, container, false);
this.mView = view;
return inflater.inflate(R.layout.fragment_fragment1, container, false);
}

Why Multiple times R.layout. ?
View view = inflater.inflate(R.layout.fragment_fragment1, container, false);
this.mView = view;
return inflater.inflate(R.layout.fragment_fragment1, container, false);
It should be One Time. At first modify here.
Note
You will get NullPointerException.
Thrown when an application attempts to use null in a case where an
object is required.
You should pass View's object .
page1 = view.findViewById(R.id.page1);
Finally
View view = inflater.inflate(R.layout.fragment_fragment1, container, false);
page1 = view.findViewById(R.id.page1);
this.mView = view;
return view;

public class fragment1 extends Fragment implements SensorEventListener {
private SensorManager mSrMgr = null;
private Sensor mLight;
private TextView page1;
protected View mView;
public fragment1() {
// Required empty public constructor
}
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
mSrMgr = (SensorManager) getActivity().getSystemService(SENSOR_SERVICE);
mLight = mSrMgr.getDefaultSensor(Sensor.TYPE_LIGHT);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_fragment1, container, false);
page1 = mView.findViewById(R.id.page1);
return mView;
}
public void onPause() {
super.onPause();
this.unregister();
}
public void onResume() {
super.onResume();
this.registerSensorListiner();
}
private void registerSensorListiner() {
mSrMgr.registerListener(this, mLight, SensorManager.SENSOR_DELAY_NORMAL);
}
private void unregister() {
mSrMgr.unregisterListener(this);
}
#Override
public void onSensorChanged(SensorEvent event) {
Toast.makeText(getContext(), String.valueOf(event.values[0]), Toast.LENGTH_SHORT).show();
page1.setText("elo"); //here is the crashing part
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}

put your findViewById code in onActivityCreated like below:
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
page1 = getActivity().findViewById(R.id.page1);
}

Sometimes when creating layouts in fragments you copy and paste xml code that has duplicate IDs. When you then call the id of the pasted resources it will try to invoke the first defined resources which is probably null at runtime. Double check if the page1 id is found only in one fragment's Xml. If not work around "findviewbyid".I hope that helps, there's little detail in your code(Error msg)

Related

SetText EditText not working in Fragment using OnStart, OnResume and onCreateView

I am using Fragment and due to some reasons, EditText is not displaying the data retrieved from a POST request which gives JSON response.
There is no issue in JSON response. I also used OnResume and OnStart methods but still nothing working.
Am I missing anthing?
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View fragment_profile = inflater.inflate(R.layout.fragment_profile, container, false);
InitializeControls(fragment_profile);
NM_Profile.getInstance(this.getContext()).ViewProfile(new IResultListener<JOM_User>() {
#Override
public void getResult(JOM_User object) {
user = object.getUser();
if(user != null) {
txtEmailAddress_Profile.setText(user.getEmailAddress());
}
}
});
return inflater.inflate(R.layout.fragment_profile, container, false);
}
#Override
public void OnStart() {
if(user != null) {
txtEmailAddress_Profile.setText(user.getEmailAddress());
}
return super.OnStart();
}
#Override
public void OnResume() {
if(user != null) {
txtEmailAddress_Profile.setText(user.getEmailAddress());
}
return super.OnStart();
}
Try initialising txtEmailAddress_Profile EditText inside the onCreateView() rather than InitializeControls().
Try something like this:
private EditText txtEmailAddress_Profile;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View fragment_profile = inflater.inflate(R.layout.fragment_profile, container, false);
InitializeControls(fragment_profile);
txtEmailAddress_Profile =(EditText) view.findViewById(R.id.YourEditText);
NM_Profile.getInstance(this.getContext()).ViewProfile(new IResultListener<JOM_User>() {
#Override
public void getResult(JOM_User object) {
user = object.getUser();
if(user != null) {
txtEmailAddress_Profile.setText(user.getEmailAddress());
}
}
});
return inflater.inflate(R.layout.fragment_profile, container, false);
}

I Cannot Change Background Color of Fragment in Android

I want to change the background color of a fragment. But when I click on the button nothing happens.
In my main activity layout XML file I imported the fragment.
Here is my code:
public class Top_Fragment extends Fragment implements View.OnClickListener {
Button button;
LinearLayout mLinearLayout;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.top_fragment, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
button = (Button) getActivity().findViewById(R.id.button);
mLinearLayout = (LinearLayout) getActivity().findViewById(R.id.layout);
}
#Override
public void onClick(View v) {
mLinearLayout.setBackgroundColor(Color.parseColor("#ffffbb33"));
}
}
Your code is perfectly but you need to add button.setOnClickListener(this);
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
button = (Button)getActivity().findViewById(R.id.button);
mLinearLayout = (LinearLayout)getActivity().findViewById(R.id.layout);
button.setOnClickListener(this); }
Replace
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.top_fragment,container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
button = (Button)getActivity().findViewById(R.id.button);
mLinearLayout = (LinearLayout)getActivity().findViewById(R.id.layout);
}
with
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View fragmentView = inflater.inflate(R.layout.top_fragment,container, false)
button = (Button)fragmentView.findViewById(R.id.button);
button.setOnClickListener(this);
mLinearLayout = (LinearLayout)fragmentView.findViewById(R.id.layout);
return fragmentView;
}

Fragment savedInstanceState not working

I have several fragments here and there's this one fragment where I want to save its state when I get back to it. I tried doing it in a testfragment where, when I click the button, the textview text will change to "test1"(The default text of the textview is "New Text"). So the textview changes the text, but when I move into another fragment and get back to it (HomeFragment), the textview is going to its default state text ("New Text"). So I think the savedInstanceState is not working because if it does, it should have "test1" when I get back to the fragment. Here's my code:
public class HomeFragment extends Fragment {
public Button button;
public TextView txt_test;
public String data_test;
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
return view;
}
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
if(savedInstanceState == null){
}
else{
data_test = savedInstanceState.getString("txt_test");
txt_test = (TextView) getActivity().findViewById(R.id.textView2);
txt_test.setText(data_test);
}
button = (Button) getActivity().findViewById(R.id.button3);
txt_test = (TextView) getActivity().findViewById(R.id.textView2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txt_test.setText("test1");
}
});
}
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("txt_test",data_test);
}
}
public class HomeFragment extends Fragment {
Button button;
TextView txt_test;
String data_test;
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
txt_test = (TextView) view.findViewById(R.id.textView2);
button = (Button) view.findViewById(R.id.button3);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txt_test.setText("test1");
}
});
if(savedInstanceState == null) {
// do nothing
} else {
data_test = savedInstanceState.getString("txt_test");
txt_test.setText(data_test);
}
return view;
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("txt_test",data_test);
}
}

Null pointer exception when setting values to TextView in Fragments

I have two fragments in my mainactivity, from the first one, the user clicks on a button and send through my listener a char to the second fragment, depends of that char a textview in the second fragment must print a text. But in my metho onActivityCreated my textview is always null.
This is my code:
FragmentOne
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
btnChefcito = (Button)getView().findViewById(R.id.btnChefcito);
btnChefcita = (Button)getView().findViewById(R.id.btnChefcita);
btnChefcito.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
welcomeListener.elegirSexo(sexo);
replaceFragment();
}
});
btnChefcita.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sexo="f";
welcomeListener.elegirSexo(sexo);
replaceFragment();
}
});
}
This is my second fragment
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tviBienvenida = (TextView)getView().findViewById(R.id.tviBienvenida);
}
public void getSex(String sex){
if(sex.equals("m")){
tviBienvenida.setText(bienvenido);
}else if(sex.equals("f")){
tviBienvenida.setText(bienvenida);
}
}
Instead of doing in onActivityCreated Do This in onCreateView:
private static View viewHolder;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
viewHolder = inflater.inflate(R.layout.YourFragmentLayout, container, false);
btnChefcito = (Button) viewHolder.findViewById(R.id.YourButtonId);
btnChefcito.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
welcomeListener.elegirSexo(sexo);
replaceFragment();
}
});
return viewHolder;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.your_fragment_id, null, false);
btnChefcito = (Button)view.findViewById(R.id.btnChefcito);
btnChefcita = (Button)view.findViewById(R.id.btnChefcita);
btnChefcito.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
welcomeListener.elegirSexo(sexo);
replaceFragment();
}
});
btnChefcita.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sexo="f";
welcomeListener.elegirSexo(sexo);
replaceFragment();
}
});
return view;
}
the problem is public void onActivityCreated(Bundle savedInstanceState) not create any view in fragment so replace all code in this method
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
sorry for my English.
On Android you have to declare a global variable.
tviBienvenida in you class, and on create view
tviBienvenida = (TextView)getView().findViewById(R.id.tviBienvenida);
The variable tviBienvenida will always have the value, and any change in tviBienvenida will also be refected to your textview.
Implement view in onCreateView method and repleace your stuff there, for example:
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.your_layout, container, false);
TextView textView = view.findViewById(R.id.yourTextView);
//your code
return view;
}

how to access the value of edittext inside fragment which is in a viewpager

I am having am mainActivity which consists of 3 fragment activity in a view pager .each fragment consists of edit texts .How to get the value of the edit text when swipe fragment horizontally ? I am trying to do like this.below code
public class MainActivity extends FragmentActivity {
int value = 0;
Context context;
String a = "";
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_main);
// Set up the action bar.
//final ActionBar actionBar = getActionBar();
// actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mAddButtonB = (Button) findViewById(R.id.addnewB);
mAddSearchV = findViewById(R.id.addnewSearch);
mAddButtonB.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
mAddSearchV.setVisibility(View.GONE);
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.customviewpager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
});
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
PageZero p0;
PageOne p1;
PageTwo p2;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
p0 = new PageZero();
p1 = new PageOne();
p2 = new PageTwo();
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return p0;
case 1:
return p1;
case 2:
return p2;
}
return null;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
// PageZero = (Fragment1)getFragmentManager().findFragmentByTag("frag1");
public class PageZero extends Fragment {
private EditText name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.componentname, container,
false);
name=(EditText)view.findViewById(R.id.nameTV);
name.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
a=name.getText().toString().trim();
Toast.makeText(getApplicationContext(),a,Toast.LENGTH_SHORT).show();
}
});/*(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
a=name.getText().toString().trim();
Toast.makeText(getApplicationContext(), a,Toast.LENGTH_SHORT).show();
return false;
}
});*/
return view;
}
}
public class PageOne extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.componentaddress, container,
false);
return view;
}
}
public class PageTwo extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.componentmobno, container,
false);
return view;
}
}
}
when i try to access the eddittext inside pageZero class like below
name=(EditText)view.findViewById(R.id.nameTV);
a=name.getText().toString().trim();
i am getting null value.help me out..Thanks in advance.
Change the pagezero class oncreateview code like this .....
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =getActivity().getLayoutInflater().inflate(R.layout.componentname,null);
name=(EditText)view.findViewById(R.id.nameTV);
name.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
a=name.getText().toString().trim();
Toast.makeText(getApplicationContext(),a,Toast.LENGTH_SHORT).show();
}
return view;
});
Return the view friend and then use default layout inflater...
At the time you click the edittext field, is there any content? Maybe you should get the text in the lost focus event of the edittext field. Thus you can enter some text first...
Example:
name.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus == false){
//get text from edittext field...
}
}
});
The way you try to get the text looks right to me. At least I do it the same way.
In the PagerAdapter's 'getItem' Method you should instantiate your fragments directly:
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new PageZero();
case 1:
return new PageOne();
case 2:
return new PageTwo();
}
return null;
}
The Viewpager only calls getItem if it wants to create a new item. Unfortunatly they called the method getItem and not createItem which would be more obvious.
Get your EditText inside onClick block...
This mean change the code from:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.componentname, container, false);
name=(EditText)view.findViewById(R.id.nameTV);
name.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
a=name.getText().toString().trim();
Toast.makeText(getApplicationContext(),a,Toast.LENGTH_SHORT).show();
}
});
return view;
}
To:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.componentname, container, false);
name.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// GET EDIT TEXT HEAR:
EditText name=(EditText)view.findViewById(R.id.nameTV);
a=name.getText().toString().trim();
Toast.makeText(getApplicationContext(),a,Toast.LENGTH_SHORT).show();
}
});
return view;
}
To create a 3 different fragments with view pager you should:
1)Create FragmentActivity with view pager and view pager adapter.
public class FragmentActivity extends FragmentActivity
{
private FragmentAdapter adapter;
private ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
adapter = new FragmentAdapter(getSupportFragmentManager());
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
}
2)Create 3 Fragments with static instance
public final class Fragment1 extends Fragment
{
public static Fragment1 newInstance() {
return new Fragment1();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
LinearLayout layout = new LinearLayout(getActivity());
// your fragment xml view
return view;
}
}
3)Fill view pager adapter with it;
public class FragmentAdapter extends FragmentPagerAdapter
{
public InstallFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return Fragment1.newInstance();
case 1:
return Fragment2.newInstance();
case 2:
return Fragment3.newInstance();
}
return null;
}
}
public class PageZero extends Fragment {
public static EditText name; //change this to public static
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.componentname, container,
false);
name = (EditText)view.findViewById(R.id.nameTV);
name.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
return view;
}
}
Then, you can access the public static EditText name (after the view for it has been generated of course) from another fragment like this.
public class PageOne extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.componentaddress, container,
false);
EditText page_one_text = PageZero.name; //you can get that variable in any fragment now, but using the class name of that fragment to access it
return view;
}
}
Cheers. Please mark this as the correct answer if it helps you. You have quite a bit of answers here
I tried below code. Working for me
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_main_explore, container, false);
ed1 = (EditText)v.findViewById(R.id.editTextTemp);
if( ed1 == null )
{
Toast.makeText(getActivity(), "ERROR UNABLE TO GET EDIT", Toast.LENGTH_LONG).show();
}
// Inflate the layout for this fragment
//return inflater.inflate(R.layout.fragment_main_explore, container, false);
return v;
}

Categories

Resources