This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
I have a problem that seems to be quite common on the internet : I have created an activity with just a fragment. This is the generated code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customer);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
ListView lv = (ListView) findViewById(android.R.id.list);
}
}
After or inside the condition, I can't get any object with findViewById: it is always null. Here is the rest of the generated code :
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_customer,
container, false);
return rootView;
}
activity_customer.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.axacs.marc.CustomerActivity"
tools:ignore="MergeRootFrame" />
the listview is actually in fragment_customer.xml:
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/new_folder_button"
android:text="" />
Does anyone know what is missing ?
use following after moving this line to onCreateView() if you want to use your listview in your fragment
ListView lv = (ListView)rootview.findViewById(android.R.id.list);
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I've got an issue with setting an adapter to the ViewPager. Each time i get a NullObjectReference error. What's wrong with my code?
1) Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.view.PagerTabStrip
android:id="#+id/pager_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingBottom="4dp"
android:paddingTop="4dp" />
</android.support.v4.view.ViewPager>
</LinearLayout>
2) Java class:
public class FoodFragment extends Fragment {
Toolbar toolbar;
ViewPager viewPager;
TabsPagerAdapter pagerAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setRetainInstance(true);
((AppCompatActivity)getActivity())
.getSupportActionBar().setDisplayShowTitleEnabled(true);
((AppCompatActivity)getActivity())
.getSupportActionBar().setTitle(R.string.food);
toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
toolbar.setBackgroundColor(Color.parseColor("#f6a632"));
pagerAdapter = new TabsPagerAdapter(getActivity()
.getSupportFragmentManager());
viewPager = (ViewPager) getActivity().findViewById(R.id.view_pager);
viewPager.setAdapter(pagerAdapter);
return inflater.inflate(R.layout.fragment_food, container, false);
}
}
I always get this error when calling viewPager.setAdapter(pagerAdapter); line.
The reason is that your onCreateView. In fragment, you need to first inflate the view for fragment first, and then findViewById from this view.
You may see an example below:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_food, container, false);
// get your view by: rootView.findViewById()
// for example:
viewPager = (ViewPager) rootView.findViewById(R.id.view_pager);
// do others...
return rootView;
}
This question already has answers here:
findFragmentByTag() returns null after perform a FragmentTransaction using replace() method
(8 answers)
Closed 6 years ago.
myFragment and myFragment2 both return null for below code. Not sure what the problem is. This solution didn't solve the problem unfortunately, it is not a duplicate.
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
NonceInputFragment nonceInputFragment = new NonceInputFragment();
transaction.add(R.id.nonce_input_fragment,nonceInputFragment,"test");
transaction.commit();
// It crashes on this line:
getSupportFragmentManager().executePendingTransactions();
NonceInputFragment myFragment = (NonceInputFragment) getSupportFragmentManager().findFragmentById(R.id.nonce_input_fragment);
NonceInputFragment myFragment2 = (NonceInputFragment) getSupportFragmentManager().findFragmentByTag("test");
}
}
nonce_input.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/nonce_input_fragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/tvLabel"
android:layout_gravity="center_horizontal" />
</LinearLayout>
NonceInputFragment
public class NonceInputFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.nonce_input, container, false);
return view;
}
}
Error message:
java.lang.RuntimeException: Unable to start activity ComponentInfo{name.com.viewpagercode/name.com.viewpagercode.MainActivity}: java.lang.IllegalArgumentException: No view found for id 0x7f0b0056 (name.com.viewpagercode:id/nonce_input_fragment) for fragment NonceInputFragment{cece542 #0 id=0x7f0b0056 test}
Your layout R.layout.identify_fragment does not have a view with android:id="#+id/nonce_input_fragment".
Specifically, this line:
transaction.add(R.id.nonce_input_fragment,nonceInputFragment,"test");
is saying "add this fragment to this activity, and put it in the container whose id is nonce_input_fragment. The exception indicates that no such view exists in your activity - meaning your layout (identify_fragment) needs to add something like this:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/nonce_fragment" />
This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
Ive been trying to load data to a listview on an android app
This is my activity that will load the listview:
public class DetallesCliente extends ActionBarActivity {
String[] data = {"S","D","A"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detalles_cliente);
ListView lista = (ListView)findViewById(R.id.listaDetalles);
ArrayAdapter<String> adaptador = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.list_content, data);
try{lista.setAdapter(adaptador);}
catch (Exception e){Log.i("WS", e.toString());}
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
ok, now this is the code in the fragment of this activity
<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:gravity="center"
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="com.example.facturas.DetallesCliente$PlaceholderFragment" >
<ListView
android:id="#+id/listaDetalles"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="27dp" >
</ListView>
<TextView
android:id="#+id/tvDetalles"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="24dp"
android:text="Detalles del Cliente"
android:textAppearance="?android:attr/textAppearanceMedium" />
the problem is when i try to load the data it is throwing me a null pointer exception, i have no fragment class cause i dont understand them, i tried to modify text from a textview and it didnt work neither
what is the correct way to allow the listview to be edited
That's not code in fragment...i hope you intended to write activity_detalles_cliente.xml code and moreover it's layout for PlaceholderFragment Fragment according to line :
tools:context="com.example.facturas.DetallesCliente$PlaceholderFragment"
You are using it for mainactivity instead(it was unable to find listview R.id.listaDetalles as it is in PlaceholderFragment's layout file) so it's showing a NullPointerException.
i have no fragment class cause i dont understand them
If i got you correct how come you have no PlaceholderFragment class and trying to create it's instance?
METHOD 1:
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_detalles_cliente, container, false);
ListView lista = (ListView)findViewById(R.id.listaDetalles);
ArrayAdapter<String> adaptador = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.list_content, data);
try{
lista.setAdapter(adaptador);
}catch (Exception e){
Log.i("WS", e.toString());}
return rootView;
}
}
add the above code (Don't forget to remove ListView lista from mainActivity) .
METHOD 2: if you don't need fragments then just remove
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
above from mainactivity and change line
tools:context="com.example.facturas.DetallesCliente$PlaceholderFragment"
to
tools:context="com.example.facturas.DetallesCliente"
While debugging another issue, I realized that the onCreateView method of one of my activities was being called twice. I'm new to programming and I don't fully understand how android calls these methods when the activity loads, but it doesn't seem right to me that it would be called twice. Eliminating most of my code, I still see my System.out message twice.
public class AddCourse extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_course);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new AddCourseFragment()).commit();
}
}
public static class AddCourseFragment extends Fragment {
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_add_course,
container, false);
System.out.println("I see this TWICE!!!!");
return rootView;
}
}
}
This is almost exactly like my main activity implementation, but that one doesn't go through onCreateView twice. Thoughts?
My activity_add_course xml was requested...
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:name="com.NsouthProductions.gradetrackerpro.AddCourse$AddCourseFragment"
android:id="#+id/AddCourseFrag"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Looks like you're adding the fragment twice. If you declare it in the xml then you don't need to add it programmatically as well.
You can remove this from your Activity's onCreate():
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new AddCourseFragment()).commit();
}
I guess everybody knows the project that is created when you choose "master detail flow" when creating your project in eclipse.
Theres layouts for the left side, for the right side and a two_pane layout with a fragment and a Framelayout as a fragment container. This works fine.
Now I have a 'main' activity A with a viewpager, fragments etc., and i call the activity from a fragment with the Callback. From that activity A I start a new activity B. That activity B is set up exactly like that example activity from eclipse that I just talked about.
Now I have the problem that the app crashes with
ERROR/AndroidRuntime(8105): Caused by: java.lang.IllegalArgumentException: Binary XML file line #57: Duplicate id 0x7f080024, tag null, or parent id 0x0 with another fragment for FragmentNumber3
When I replace the fragment in the two_pane layout with another framelayout, it doesn't crash.
This problem is typical for nested fragments, but I don't have nested fragments here, right? I have an activity B that, at that point, doesn't have anything to do with my activity A.
What's the problem here?
Edit: This is my Activity B:
public class SucheActivity extends FragmentActivity implements
SearchboxFragment.SearchboxListener {
private boolean mTwoPane;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchbox);
getActionBar().setDisplayHomeAsUpEnabled(true);
if (findViewById(R.id.searchresult_container) != null) {
mTwoPane = true;
}
}
}
And thats the two_pane layout for the activity, the searchbox should be left, the searchresults right:
<LinearLayout 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:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:baselineAligned="false"
android:divider="?android:attr/dividerHorizontal"
android:orientation="horizontal"
android:showDividers="middle" >
<fragment
android:id="#+id/searchbox_fragment"
android:name="com.example.layouttest.SearchboxFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
<FrameLayout
android:id="#+id/searchresult_container"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3" />
</LinearLayout>
Heres the SearchboxFragment class:
public class SearchboxFragment extends Fragment {
SearchboxListener mCallback;
View v;
public interface SearchboxListener {
public void onSearchStarted();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.searchbox, container, false);
return v;
}
}
The searchresultfragment:
public class SearchResultFragment extends Fragment {
public SearchResultFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.searchresult, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
And the refs.xml in res/values-large:
<resources>
<item name="searchbox" type="layout">#layout/haussuche_twopane</item>
</resources>
Okay, so this is what I found out:
I cant set the layout of my Activity to searchbox.xml (and have it alias'd in refs.xml with two_pane.xml) AND set the Layout of SearchboxFragment to searchbox.xml.
I thought that searchbox.xml was never shown by the Activity in two-pane-mode, I could safely set it elsewhere, but that's wrong.
What I did was copy that layout and use a searchbox_onepane.xml and searchbox_twopane.xml.