Nullpointerexception thrown when trying to findViewById - java

I have the following Activity:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new StartFragment())
.commit();
}
Button login = (Button) findViewById(R.id.loginButton);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this,LoginActivity.class);
startActivity(intent);
}
});
}
I get a NPE when I try to invoke findViewByID for R.id.loginButton, and I'm guessing this is because loginButton is within a separate Fragment, which I have as:
public static class StartFragment extends Fragment {
public StartFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
}
However, I am unsure of how to fix this so that I can find the loginButton ID. I haven't worked with fragments before, so I realize I may be using them/implementing them incorrectly. fragment_main contains a few buttons in a LinearLayout, and activity_main has nothing but a single FrameLayout.

Try to implement your onCreateView(...) in Fragment like
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
View something = rootView.findViewById(R.id.something);
something.setOnClickListener(new View.OnClickListener() { ... });
return rootView;
}
The Button is in the fragment layout (fragment_main.xml) and not in the activity layout (activity_main.xml). onCreate() is too early in the lifecycle to find it in the activity view hierarchy, and a null is returned. Invoking a method on null causes the NPE.

Write code to initialize button from fragment becuase your button is into fragment layout not into activity's layout.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
Button login = (Button) rootView.findViewById(R.id.loginButton);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this,
LoginActivity.class);
startActivity(intent);
}
});
return rootView;
}
And remove the login button related code from onCreate of Activity.

findViewById() works with reference to a root view.
Without having a view in the first place will throw a null pointer exception
In any activity you set a view by calling setContentView(someView);.
Thus when you call findViewById() , its with reference to the someView.
Also findViewById() finds the id only if its in that someView. So in you case null pointer exception
For fragments, adapters, activity, .... any view's findViewById() will only find if the id exixts in the view
Alternately if you are inflating a view, then you can also use inflatedView.findViewById() to get a view from that inflatedView
In short make sure you have the id in your layout you are referring to or make findViewById() call in appropriate place(Ex. adapters getView(), activity's onCreate() or onResume() or onPause() , fragments onCreateView(), ....)
Also have an idea about UI & background thread's as you cannot efficiently update UI in bg-threads

Related

Android Studio - Fragment button action

I tried to make an application that shows a fragment at start then you can change that fragment to an other one with a button in the first fragment. But when I put the button action in the fragments java, it won't start and I get the nullpointerexception error. Could you tell me why?
public class Fragment_main extends Fragment {
FragmentManager fm = getFragmentManager();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Button button_inditas = (Button) getView().findViewById(R.id.button_inditas);
button_inditas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fm.beginTransaction().replace(R.id.content_frame, new Fragment_1()).commit();
}
});
return inflater.inflate(R.layout.fragment_main,container,false);
}
}
But when I put the button action in the fragments java, it won't start and I get the nullpointerexception error. Could you tell me why?
Well I see some errors on your code...
First of all you can't call getView() if you haven't inflated one, it means that you MUST inflate a view as i'll put on my answer and then you can avoid the getView() and use that view itself.
And instead of returning the inflater you have to return your View
This is how your Fragment should look like:
public class Fragment_main extends Fragment {
public Fragment_main() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main,container,false);
Button button_inditas = (Button)rootView.findViewById(R.id.button_inditas);
button_inditas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager ();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction ();
fragmentTransaction.add (R.id.content_frame, new Fragment_1());
fragmentTransaction.commit ();
});
return rootView;
}
}
You have to inflate the view first and use the view returned by that instead of getView ().
View view = inflater.inflate (...);
and then
... = (Button) view.findView(...);
This happens because the view that is returned by getView () hasn't been created yet, so getView() returns null.

Android - where to put onClick on linearlayout of a fragment

Obviously, I am new to Android - XML programming... So I have a navigation drawer, and once item is selected from the drawer, a corresponding fragment on the right side will display. Inside that fragment, I have linear layouts. I'd like to get redirected to another activity once that linear layout has been tapped. I was able to make it work on activities, by using android:onClick on XML file, but can't make it work on fragment. Somebody help me please.
App interface, refer to this image:
http://i.stack.imgur.com/u6dHi.jpg
Code:
fragment_smart.xml - the display once item's selected. I am trying to use the onClick on xml.
<LinearLayout
android:id="#+id/linearLayoutsmart1"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_below="#+id/smart_title"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
android:orientation="horizontal"
android:weightSum="1"
android:onClick="smart_recommended_link">
Here's my Java code:
public class FragmentSmart extends Fragment {
public static final String TAG = "stats";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myfragment = inflater.inflate(R.layout.fragment_smart, container, false);
return myfragment;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public void smart_recommended_link(View view) {
Intent smartRecommendedIntent = new Intent(this, SmartRecommended.class);
startActivity(smartRecommendedIntent);
}
}
The app is crashing when I clicked on the linearlayout using this code. What's the best thing to do here? Thank you!
For fragments you need to add the listener programmatically:
public class MyFragment extends Fragment implements View.OnClickListener {
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.my_layout).setOnClickListener(this);
}
#Override
public void onClick(View v) {
// Handle click based on v.getId()
}
}
First of all, linear layouts cant trigger onClick events by default.
Check this answer for more information: LinearLayout onClick.
You can get the LinearLayout from the view in your onCreateView() like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myfragment = inflater.inflate(R.layout.fragment_smart, container, false);
LinearLayout layout = (LinearLayout)myFragment.findViewById(R.id.linearLayoutsmart1);
// here you can set a listener of any type you want to the layout
return myfragment;
}
In fragments, you must use getActivity() method instead of this to reference the activity that the fragment is attached to.
public void smart_recommended_link(View view) {
Intent smartRecommendedIntent = new Intent(getActivity(), SmartRecommended.class);
startActivity(smartRecommendedIntent);
}

Refresh value in editext using addToBackStack

I have two fragment, "A" and "B".
When I return (BackPressed) to my fragment "A", the values of edittext aren't refresh. Why?
I have this code to call fragment "B".
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_container_pedido_novo,
container, false);
btnAddProduto = (Button) view.findViewById(R.id.btnNovoProduto);
btnAddProduto.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Fragment fragment = new FragmentContainerProduto(true);
FragmentManager frgManager = getActivity()
.getSupportFragmentManager();
frgManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.addToBackStack(null).commit();
}
});
edtCodPedido = (EditText) view.findViewById(R.id.edtCodPedidoNovo);
edtVlBruto = (EditText) view.findViewById(R.id.edtVlBrutoPedidoNovo);
edtCodPedido
.setText(String.valueOf(GlobalUtil.objPedido.getCodPedido()));
edtVlBruto.setText(String.valueOf(GlobalUtil.objPedido.getVlBruto()));
return view;
}
Someone?
When you return to a fragment from the back stack Android does not re-create the fragment but re-uses the same instance of it and starts with onCreateView() in the fragment lifecycle. The key thing is you should not inflate view again in onCreateView() of the fragment to which you return, because you are using the existing fragment instance. You need to save and reuse the rootView. See here the answer of Vince Yuan How can I maintain fragment state when added to the back stack?.
Well, I just need put this code...
#Override
public void onResume() {
super.onResume();
edtVlBruto.setText(String.valueOf(GlobalUtil.objPedido.getVlBruto()));
edtCodPedido
.setText(String.valueOf(GlobalUtil.objPedido.getCodPedido()));
}

#override error showing up in .xml file

I've just moved my button onCreatView from my activity_main.java file to the correct file - my ConvertFragment.java file.
Now that I've copy and pasted the code, I'm getting a red-x errors on all of my findViewById's... any thoughts?
thanks in advance!
public class ConvertFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_convert, container, false);
final EditText editDecimal = (EditText) findViewById(R.id.editDecimal);
final EditText editBinary = (EditText) findViewById(R.id.editBinary);
Button buttonConvert = (Button) findViewById(R.id.buttonConvert);
buttonConvert.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
int decimal = Integer.valueOf(editDecimal.getText().toString());
editBinary.setText(Integer.toBinaryString(decimal));
}
});
return rootView;
}
}
It's because a fragment doesn't have a method findViewById().
You can either call that method on your activity:
getActivity().findViewById()
Or just use the layout that you've just inflated and find view's inside of it:
rootView.findViewById()
The 2nd one is better (IMO) as it doesn't rely on the activity.

SlidingMenu in Child Activities Navigation Android

I am trying to add left side slide menu inside my application but i am facing little trouble getting the slide menu to the following child activities of the fragment.
So far i have tried using this sliding menu example and when i got this image now inside the "Find People" fragment class i have static data.
Find People (Parent Activity) on Button Click go to ---> Friends (Child Activity of Find People) on Button Click go to ----> Names (Child Activity of Friends)
I am trying to get the same sliding menu with the Child Activities also that i failed to achieve so far please can any one help me out
public class FindPeopleFragment extends Fragment {
public FindPeopleFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_find_people, container, false);
Button btn = (Button) rootView.findViewById(R.id.butto);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), Friends.class);
startActivity(intent);
}
});
return rootView;
}
}
Friends (Child Activity)
public class Friends extends Activity {
Button btnNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.friends_xml);
btnNext = (Button)findViewById(R.id.btnNexts);
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Go to Names Child Activity
}
});
}
}
And Similarly Names (Child Activity)
How do i get the same slide menu in both the child activities (Friends & Names). Any idea ??
Plz help me out in this.
Code Snippet will be much helpful.
Thanks
As #Piyush Gupta said you need to call new Fragment instead of calling activities,
In Place of activity you need to use Fragment and move from one Fragment to next used this code
Instead of using Fragment element use Framelayout id of the fragment Xml
Replace ur code with this
public class FindPeopleFragment extends Fragment {
public FindPeopleFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_find_people, container, false);
Button btn = (Button) rootView.findViewById(R.id.butto);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FragementDemo fd = new FragementDemo();
android.support.v4.app.FragmentTransaction ft =
getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fd); // content_frame is your FrameLayout container
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
});
return rootView;
}
}
And your next child activity will extend Fragment not Activity like this :
public class Friends extends SherlockFragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragementdemo, container, false);
// use button click code as used in FindPeopleFragment
return rootView;
}
}
Hope it works fine now for you!!

Categories