I'm trying to add a spinner and a listener in my fragment. Android studio did not report any error to me, but when I run it, it crashes with this FATAL EXCEPTION:
14267-14267/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: space.markwen.www.units, PID: 14267
java.lang.RuntimeException: Unable to start activity ComponentInfo{space.markwen.www.units/space.markwen.www.units.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2456)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2539)
at android.app.ActivityThread.access$900(ActivityThread.java:159)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1384)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:152)
at android.app.ActivityThread.main(ActivityThread.java:5507)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at space.markwen.www.units.LengthActivity.onCreate(LengthActivity.java:40)
at android.app.Fragment.performCreate(Fragment.java:2198)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:942)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1148)
at android.app.BackStackRecord.run(BackStackRecord.java:793)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1535)
at android.app.FragmentController.execPendingActions(FragmentController.java:325)
at android.app.Activity.performStart(Activity.java:6320)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2419)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2539)
at android.app.ActivityThread.access$900(ActivityThread.java:159)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1384)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:152)
at android.app.ActivityThread.main(ActivityThread.java:5507)
at java.lang.reflect.Method.invoke(Native Method)
Fragment class:
public class LengthActivity extends Fragment {
View lengthView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Change FrameLayout to content_length
lengthView = inflater.inflate(R.layout.content_length, container, false);
// Change the title on titlebar to Length
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("Length");
return lengthView;
}
Spinner spinner;
String[] lengthUnits = {
"Kilometer", "Meter", "Centimeter", "Millimeter", "Micrometer", "Nanometer", "Mile", "Yard", "Foot", "Inch", "Nautical Mile"};
#Override
public void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
spinner = (Spinner) getView().findViewById(R.id.lengthSpinner);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
ArrayAdapter<String> adapter = new ArrayAdapter<String> (getActivity(), android.R.layout.simple_spinner_item, lengthUnits);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
}
And my view just in case you can find something out of it:
<?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:weightSum="1">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/editText"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="30dp"
android:layout_weight="1.01" />
<Spinner
android:layout_width="112dp"
android:layout_height="57dp"
android:id="#+id/lengthSpinner" />
<!--android:layout_below="#+id/editText"-->
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="42dp" />
</LinearLayout>
Thanks
Move all of your onCreate() code — starting with the line that is crashing — into onViewCreated(). You cannot execute any of that until onCreateView() has been called, and onCreate() will be called before onCreateView(). onViewCreated() is called after onCreateView().
As advised by CommonsWare, the basic components of a working example would look like this:
enter public class Booking extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_booking, container, false);
return rootView;
}
public void onViewCreated(View rootView, Bundle savedInstanceState){
super.onViewCreated(rootView, savedInstanceState);
final View v = rootView;
// Spinner element
Spinner spinner = (Spinner) rootView.findViewById(R.id.spinner);
//spinner.setOnItemClickListener(this);
// Spinner Drop down elements
List<String> categories = new ArrayList<String>();
categories.add("4 Night / 5 Days");
categories.add("5 Night / 6 Days");
categories.add("6 Night / 7 Days");
categories.add("7 Night / 8 Days");
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
// Spinner click listener
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
Related
RecyclerView works normally when used in activity but when used in fragment it gives error as below
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)' on a null object reference
at restaurant.menu.fragments.MealsFragment.onCreate(MealsFragment.java:42)
fragment_meals.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".fragments.MealsFragment">
<!-- TODO: Update blank fragment layout -->
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvMeals"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MealsFragment.java
public class MealsFragment extends Fragment {
public MealsFragment() {
// Required empty public constructor
}
RecyclerView recyclerView;
itemAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<Items> ItemsList;
ItemsList= (ArrayList<Items>) RoomDatabaseSingleton.getInstance(getActivity().getApplicationContext())
.getAppDatabase()
.getDao()
.getItems("Meals");
recyclerView = getActivity().findViewById(R.id.rvMeals);
RecyclerView.LayoutManager manager = new LinearLayoutManager(getActivity(),RecyclerView.VERTICAL,false);
recyclerView.setLayoutManager(manager);
adapter = new itemAdapter(getActivity().getApplicationContext(), ItemsList);
recyclerView.setAdapter(adapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_meals, container, false);
}
}
As per the Fragment lifecycle guide, onCreate() is called before onCreateView. That means that your Fragment's view hasn't been created yet.
Instead, you want to move all of your code from onCreate() into onViewCreated() - that is the method that is called after onCreateView() and is where you can access your newly inflated views. Note that you cannot and should not be using getActivity().findViewById() - that finds views in your activity's layout, not in your fragment's layout:
public class MealsFragment extends Fragment {
public MealsFragment() {
// Required empty public constructor
}
RecyclerView recyclerView;
itemAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_meals, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
ArrayList<Items> ItemsList = (ArrayList<Items>) RoomDatabaseSingleton.getInstance(getContext().getApplicationContext())
.getAppDatabase()
.getDao()
.getItems("Meals");
recyclerView = view.findViewById(R.id.rvMeals);
RecyclerView.LayoutManager manager = new LinearLayoutManager(
getContext(), RecyclerView.VERTICAL,false);
recyclerView.setLayoutManager(manager);
adapter = new itemAdapter(getContext(), ItemsList);
recyclerView.setAdapter(adapter);
}
}
I am new to android and is in need for some little help.I have a xml layout called fragment_home.xml which contains some images.I want to redirect the user to another page(fragment_about_sl.xml) when the user clicks on an image.Please tell me how to do that and where to place the codes.
fragment_home.xml(layout with the images)
<LinearLayout
android:id="#+id/home"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.sloid.destinations.navigationdrawerfragments.homeFragment"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_horizontal">
<ImageView
android:id="#+id/aboutslbtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:src="#drawable/aboutsl"
/>
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:layout_marginBottom="10dp"
android:src="#drawable/toplandmarks"
/>
</LinearLayout>
</ScrollView>
</LinearLayout>
fragment_about_sl.xml(the layout that should be redirected once image is clicked)
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/aboutslscrollview"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.sloid.destinations.navigationdrawerfragments.aboutSLFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="250dp" />
<LinearLayout
android:id="#+id/SliderDots"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#id/viewPager"
android:layout_marginBottom="20dp"
android:gravity="center_horizontal"
android:orientation="horizontal" />
</RelativeLayout>
</LinearLayout>
</ScrollView>
I also added the java file if its necessary.
homeFragment.java(java file for fragment_home.xml)
public class homeFragment extends Fragment {
public homeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("Destinations");
}
}
aboutSLFragment.java(java file for fragment_about_sl.xml)
public class aboutSLFragment extends Fragment{
ViewPager viewPager;
LinearLayout sliderDotspanel;
private int dotscount;
private ImageView[] dots;
TextView aboutsltext;
Button readmorebtn;
public aboutSLFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_about_sl, container, false);
viewPager = (ViewPager) rootView .findViewById(R.id.viewPager);
sliderDotspanel = (LinearLayout)rootView.findViewById(R.id.SliderDots);
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getContext());
viewPager.setAdapter(viewPagerAdapter);
dotscount = viewPagerAdapter.getCount();
dots = new ImageView[dotscount];
for(int i = 0; i < dotscount; i++){
dots[i] = new ImageView(getContext());
dots[i].setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.non_active_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8, 0);
sliderDotspanel.addView(dots[i], params);
}
dots[0].setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.active_dot));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for(int i = 0; i< dotscount; i++){
dots[i].setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.non_active_dot));
}
dots[position].setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.active_dot));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
aboutsltext=(TextView)rootView.findViewById(R.id.aboutsltext);
readmorebtn=(Button)rootView.findViewById(R.id.readmorebtn);
readmorebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (readmorebtn.getText().toString().equalsIgnoreCase("Read More"))
{
aboutsltext.setMaxLines(Integer.MAX_VALUE);//your TextView
readmorebtn.setText("Read Less");
}
else
{
aboutsltext.setMaxLines(3);//your TextView
readmorebtn.setText("Read More");
}
}
});
// Inflate the layout for this fragment
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("About Sri Lanka");
}
code added to change the fragment
rootView.findViewById(R.id.aboutslbtn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new aboutSLFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.home, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
logcat
30388-30388/com.example.sloid.destinations E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sloid.destinations, PID: 30388
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sloid.destinations/com.example.sloid.destinations.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2702)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.example.sloid.destinations.navigationdrawerfragments.homeFragment.onCreateView(homeFragment.java:30)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2354)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1419)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1809)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:799)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2580)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2229)
at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3221)
at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3171)
at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:192)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:560)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1234)
at android.app.Activity.performStart(Activity.java:6329)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
Just add ids to those images and handle onclick events inside your fragment. You can find the image view using findViewById(R.id.'yourId');
And the onClick listener set: view.setOnClickListener(...);
As per My comment
Reference : Fragment replace
Fragment fragment = new aboutSLFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.home, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Tutorial : https://www.javacodegeeks.com/2013/06/android-fragment-transaction-fragmentmanager-and-backstack.html
You are new in android right, first of all you need to check Fragment detail
As you question you need to replace or add fragment as #Vishva Dave said
Follow this link
private void loadFragment(Fragment fragment) {
// create a FragmentManager
FragmentManager fm = getFragmentManager();
// create a FragmentTransaction to begin the transaction and replace the Fragment
FragmentTransaction fragmentTransaction = fm.beginTransaction();
// replace the FrameLayout with new Fragment
fragmentTransaction.replace(R.id.frameLayout, fragment);
fragmentTransaction.commit(); // save the changes
}
First you need to add android:id="#+id/imageId" to the <ImageView ... in the xml, then in your homefragment add this code:
public class homeFragment extends Fragment {
View rootView;
public homeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_home, container, false);
rootView.findViewById(R.id.imageId).setOnClickListener(new OnClickListener(){
// go to the other fragment using fragmentTransaction
});
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments
different titles
getActivity().setTitle("Destinations");
}
}
Im having trouble when creating an ArrayAdapter on my spinner. i don't know how to explain to you guys but people say a picture speaks 1000 words. so i provide a picture of my problem. please help me i really dont know what to do know.
this is my class
public class SettingFragment extends Fragment{
private View rootView;
Spinner spinner;
ArrayAdapter<CharSequence> adapter;
public SettingFragment(){
//required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_setting, container, false);
spinner = (Spinner)rootView.findViewById(R.id.spinner);
adapter = ArrayAdapter.createFromResource(this, R.array.select_font_size, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
return rootView;
}
}
this is my string.xml
<string-array name="select_font_size">
<item>Small</item>
<item>Default</item>
<item>Large</item>
<item>Larger</item>
</string-array>
and this is my xml code
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner"
android:layout_gravity="center_horizontal" />
I'd suggest to move the creation of the adapter inside the onActivityCreated callback when you know for sure that by calling getActivity() you will get a not null instance of the activity:
public class SettingFragment extends Fragment{
private View rootView;
Spinner spinner;
ArrayAdapter<CharSequence> adapter;
public SettingFragment(){
//required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_setting, container, false);
spinner = (Spinner)rootView.findViewById(R.id.spinner);
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
adapter = ArrayAdapter.createFromResource(getActivity(), R.array.select_font_size, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
}
Try using the Application context, or context of the activity instantiating the fragment.
adapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.select_font_size, android.R.layout.simple_spinner_item);
OR
adapter = ArrayAdapter.createFromResource(YOUR_ACTIVITY_CONTEXT_TO_BE_PASSED_INTO_FRAGMENT, R.array.select_font_size, android.R.layout.simple_spinner_item);
i am getting this errors.
Process: com.example.user.timey, PID: 17619
java.lang.RuntimeException: Your content must have a ListView whose id
attribute is 'android.R.id.list'
I have already defined android:id="#android:id/list" in my listview in xml.
This is my xml code:
<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="com.example.user.timey.OneFragment">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:divider="#E6E6E6"
android:dividerHeight="1dp" >
</ListView>
</RelativeLayout>
And this is my java code:
public class OneFragment extends ListFragment {
View rootView;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
DBController controller = new DBController(getActivity());
ArrayList<HashMap<String, String>> scheduleList = controller.getAllSchedules();
if (scheduleList.size()!=0){
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
SimpleAdapter adapter = new SimpleAdapter(getActivity(), scheduleList, R.layout.view_schedule_entry, new String[] { "scheduleId",
"scheduleName", "scheduleStartTime" }, new int[] {
R.id.scheduleId, R.id.scheduleName, R.id.scheduleTime });
setListAdapter(adapter);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_one, container, false);
return rootView;
}
Anyone knows whats wrong with my code? Thanks alot.
In your layout add id for ListView like this -
android:id="#+id/list"
Do not assign id to your views in layouts like #android:id/list.
Then in your onCreateView() method code get a reference to it -
ListView lv = (ListView) rootView.findViewById(R.id.list);
I am creating an application which consists of a viewpager with different fragments.And these fragments contains different imagebuttons.I want to open fragments when each of these image button is clicked.But i don't know how to do it.I am new to fragments and i don't know much about them.I am trying to make this code since 2 days.Please if you can help me out.So i will be able to complete my project app.
My layout for NoticeBoard.java is as below: This contains2 imagebuttons and a listview.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns : android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:id="#+id/relative">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:background="#AAAAAA"
android:id="#+id/line">
<ImageButton
android:id="#+id/ptu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:background="#CCCCCC"
android:clickable="true"
android:onClick="OnClick"
android:contentDescription="#string/mko"
android:paddingBottom="10dp"
android:paddingLeft="9.9dp"
android:paddingRight="20dp"
android:paddingTop="10dp"
android:src="#drawable/img" />
<ImageButton
android:id="#+id/ku"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="1dp"
android:background="#CCCCCC"
android:clickable="true"
android:contentDescription="#string/mn"
android:paddingBottom="10dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="10dp"
android:src="#drawable/image" />
</LinearLayout>
<ListView
android:id="#+id/nb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/line"
android:layout_alignParentTop="true"
>
</ListView>
</RelativeLayout>
And my layout for the ptu,cu,ku,htu is same as above but with different adapter set on the above same listview.I have defined different adapters for ptu,hptu,cu and ku in their .java classes
My NoticeBoard.java class is a fragment with the noticeboard layout set as view and a listview.
public class Notice_Board extends Fragment {
ListView l;
ImageButton i1,i2,i3,i4;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_noticeboard, container, false);
l = (ListView) rootView.findViewById(R.id.nb);
String[] title = new String[]{"Important Announcements", "Datesheet", "Results","Placement Drives","Admissions","Entrance exams"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, title);
l.setAdapter(adapter);
i1 = (ImageButton ) rootView
.findViewById(R.id.ptu);
i2 = (ImageButton ) rootView
.findViewById(R.id.cu);
i3 = (ImageButton ) rootView
.findViewById(R.id.ku);
i4 = (ImageButton ) rootView
.findViewById(R.id.hptu);
i1.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.layout.activity_noticeboard,new PTU(),"PTU");
}
return rootView;
}
}
Below is my ptu.java class that contains the same view and the listview same as noticeboard but setting different values to listview by setting adapter with different values on it.
public class PTU extends Fragment{
ListView l;
ImageButton i2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_noticeboard, container, false);
String[] array = new String[] {"Important Announcements", "Results",Programme","Syllabus","Fees","Events","Placement Drives"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, array);
l = (ListView) rootView.findViewById(R.id.nb);
l.setAdapter(adapter);
return rootView;
}
}
I want that each time a button is clicked the layout for notice board should appear but with different listview.And i also want when the noticeboard layout opens the ptu imagebutton should appear clicked having the listview in its fragment.
Below is my ku.java class that contains the same view and the listview that is for ptu but setting different values to listview by setting adapter with different values on it.
public class KU extends Fragment{
ListView l;
ImageButton i2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_noticeboard, container, false);
String[] array = new String[] {"Important Announcements", "Results",Programme","Syllabus","Fees","Events","Placement Drives"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, array);
l = (ListView) rootView.findViewById(R.id.nb);
l.setAdapter(adapter);
return rootView;
}
}
I think issue is in your initialisation of fragment manager.
FragmentManager fm = getFragmentManager();
Instead of it, use
FragmentManager fragmentManager = ((MainActivity)getActivity()).getSupportFragmentManager();
Here MainActivity is your fragment activity from which you are calling your all fragments.
You have a Main fragment manager Activity name fragment activity. this is the main fragment activity manager. you have to set all fragment using by this activity.
i1 = (ImageButton ) rootView
.findViewById(R.id.ptu);
i2 = (ImageButton ) rootView
.findViewById(R.id.cu);
i3 = (ImageButton ) rootView
.findViewById(R.id.ku);
i4 = (ImageButton ) rootView
.findViewById(R.id.hptu);
i1.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
fragmentActiivty.setFragment();
}
Notes: :SetFragment function is made in fragment-activity class
public static void set_view_FAQ() {
FragmentManager fm = act.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment fragment = new yourFragnmentName();
ft.add(R.id.activity_main_content_fragment, fragment);
ft.commit();
}
Note: new yourFragmentNAme means yous fragment class likes Ku,ptu,etc