createFromResources() in ArrayAdapter cannot be applied to spinner - java

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

Related

RecyclerView crashes with NullPointerException in Fragment

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

setOnItemSelectedListener() for spinner in Fragment

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

ListView 'android.R.id.list' is not found in ListFragment

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

textView.setText not working

I have a TextView in a fragment called "frontpage". In my MainActivity (also called frontpage, and the fragment is also there), I want to change the text of my textview. Here is my code in the Mainactivity:
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_frontpage, container, false);
return rootView;
}
public void setText(String text){
TextView textView = (TextView) getView().findViewById(R.id.NameView);
textView.setText("HI!");
}
}
And here is my code in the xml layout for the textview:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/NameView"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true" />
No errors are being shown, but when running the app, the textview stays empty. Why is that?
Because you never called your setText(String) function! JVM will follow what you tell it to and you never asked it to go and execute seText(String) function :)
Add this code above return rootView.
setText("Hi");
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_frontpage, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.NameView);
textView.setText("Hi");
return rootView;
}

Imagebutton inside a fragment clicked to open a new fragment

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

Categories