android list view null pointer because of fragments [duplicate] - android

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"

Related

findFragmentById returns null for Fragment that has been added using FragmentTransaction [duplicate]

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" />

Adding a listview as on of the views that can be selected in a navigation drawer

First off; I would like to apologize for the lengthy question. I though this was the only way to get across what I am trying to do. Anyway. I have an app that user a navigation drawer that will offer a user 3 choices. I want Test1Fragment to be a listview. I can not seem to figure out how to make this happen. Please help.
MainActivity method that controls which fragment is loaded based on the selection:
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new Test1Fragment();
break;
case 1:
fragment = new Test2Fragment();
break;
case 2:
fragment = new Test3Fragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
Test1Fragment:
public class Test1Fragment extends Fragment {
public Test1Fragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_create, container, false);
return rootView;
}
fragment_create.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!--<TextView-->
<!--android:id="#+id/txtLabel"-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:layout_centerInParent="true"-->
<!--android:text="Create View"-->
<!--android:textSize="16dp" />-->
<!--<ImageView-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:layout_below="#id/txtLabel"-->
<!--android:layout_centerHorizontal="true"-->
<!--android:layout_marginTop="10dp"-->
<!--android:src="#drawable/ic_action_copy" />-->
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
I understand that I am missing code for the listview, but this is all I want int the xml view.
Thank you
In your current implementation, your layout code should look in example like that:
<?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">
<ListView
android:id="#+id/layout_fragment_listView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
Then in your class, you must fill listview with data. You have to create adapter and attach data to this adapter. Then adapter must be passed to listview.
Quick example :
public class Test1Fragment extends Fragment {
//No need for empty constructor, it is made by default
//public Test1Fragment() {
//}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_create, container, false);
ListView listView =(ListView)rootView.findViewById(R.id.layout_fragment_listView);
String[] items = { "Milk", "Cheese", "Cucumber", "Toilet", "Duck" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
return rootView;
}
This way you will have filled listview with strings from array items.
This is very basic example, you can extend also base adapter, and populate it with your own objects and views.
Here is screenshot with result :

Android fragment - findViewById returns null [duplicate]

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);

Why is my onCreateView method being called twice?

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();
}

findFragmentById is always null

Trying to find a ListFragment in the xml layout is always returning null. I'm using SherlockFragmentActivity with a SherlockListFragment. Here is the code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_custom_layout);
adapter = new My_Custom_Adapter(this, My_Object, My_Object_2);
}
// Create the list fragment and add it as the list content.
if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) {
mListFragment list = new mListFragment();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, list).commit();
}
}
public static class mListFragment extends SherlockListFragment {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(adapter);
setListShown(true);
}
}
This is a shortened version of the xml layout:
<RelativeLayout
android:id="#+id/top_control_bar">
<!-- Text Views -->
</RelativeLayout>
<RelativeLayout >
<!-- Button -->
</RelativeLayout>
<LinearLayout
android:id="#+id/start_data"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/top_control_bar"
android:orientation="vertical" >
<fragment
android:name="android.support.v4.app.ListFragment"
android:id="#android:id/content"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
findFragmentById(android.R.id.content)
always returns null. Why can't it find the fragment within my layout?
The problem that you have is that you declared in the xml the Fragment as a ListFragment.
getSupportFragmentManager().findFragmentById(android.R.id.content) uses Support fragment manager, so you will need a SupportMapFragment
Try this:
<fragment
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="#android:id/content"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
Shouldn't
android:id="#android:id/content"
be
android:id="#+id/content"
?
From the documentation it seems like you are using the wrong syntax.
I'm also not sure your chained methods will work correctly as written. Change
getSupportFragmentManager().beginTransaction().add(android.R.id.content, list).commit();
to
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(android.R.id.content, list);
transaction.commit();
even then, I honestly don't know what you'd be trying to do there. You are aware that FragmentTransaction's add method as you're using it is trying to add a fragment to a container which, in your if, already was established as having a null value?
Try this in mListFragment class override onCreate() and call setRetainInstance(true);
public static class mListFragment extends SherlockListFragment {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(adapter);
setListShown(true);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
}

Categories

Resources