Error populating spinner in a fragment - android

I have a Activity with two fragments. One of them hava a spinner. When I populate it the app crashes.
I don't know why. In android developers it's confused how do it in fragments, it seems is diferent like normal activity.
Thanks!
public class InstrumentsFrag extends Fragment {
TextView tv1;
Spinner sp;
String[] os = {"Cupcake v1.5", "Donut v1.6", "Éclair v2.0/2.1", "Froyo v2.2",
"Gingerbread v2.2", "Honeycomb v3.0/3.1"};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.instruments, container, false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sp = (Spinner) getActivity().findViewById(
R.id.spinner1);
ArrayAdapter <CharSequence>adapter = ArrayAdapter.createFromResource( getActivity(), R.array.sections , android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
}

I had the same problem where my app crashed when populating a spinner. In my case, the spinner I was populating was defined in the fragment's XML file, so the trick was getting findViewById() to find it. I see in your case you tried to use getActivity():
sp = (Spinner) getActivity().findViewById(R.id.spinner1);
I also tried using both getActivity() and getView(), and both caused crashes (null spinner, and NULL Pointer exception respectively).
I finally got this to work by replacing getActivity() with the fragment's view. I did this by populating the spinner when onCreateView() is called. Here are some snippets from my final code:
private Spinner spinner;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.myFragmentXmlFile, container, false);
// Now use the above view to populate the spinner.
setSpinnerContent( view );
...
}
private void setSpinnerContent( View view )
{
spinner = (Spinner) view.findViewById( R.id.mySpinner );
...
spinner.setAdapter( adapter );
...
}
So I passed the fragment view into my function and referenced that view to configure the spinner. That worked perfectly. (And quick disclaimer - I'm new to Android myself, so perhaps some of the above terminology can be corrected or clarified if needed by more experienced people.)
Hope it helps!

Related

using "this" in a fragment gives me an error

public class Home extends Fragment {
ArrayList<String> notes = new ArrayList<String>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ListView listView = (ListView) getActivity().findViewById(R.id.listView);
notes.add("Example note");
ArrayAdapter arrayAdapter =new ArrayAdapter(this, android.R.layout.simple_list_item_1,notes);
listView.setAdapter(arrayAdapter);
return inflater.inflate(R.layout.home,container,false);
}
when i use this it gives me an error, tried using getactivity or getcontext and both crash the app when i do it
where did i go wrong
any suggestions are welcomed and thanks in advance <3
You must get corresponding fragment view by below 2 lines
View myView = inflater.inflate(R.layout.fragment_view, container, false);
ListView lv = myView.findViewById(R.id.listView);
getActivity() may be null while your fragment is in process of preparation.
Just inflate your fragment layout in onCreateView and place ListView logic to onViewCreated() or onActivityCreated
Get listview from fragment by inflate, not from parent activity
ArrayAdapter needs a context as the first parameter, so either use this.getContext() or this.getActivity() instead of passing this, which is a fragment.
Furthermore, you should move the code into onViewCreated method, as the view must be inflated before you access its elements.
And you have to use view.findViewById() instead of getActivity().
For some reason Fragments do not inherit the context from an Activity. Try this:
ListView listView = ((ListView) getActivity()).findViewById(R.id.listView);
Same works for getContext.
Context context = ((ListView) getActivity)).getApplicationContext();

Where should I put logic in the Java tab layouts

I have 2 fragments each fragments has a different java logic. Where should i put the java logic? if i did put it in the fragments,then error message displays :
cannot resolve method findViewById, Cannont resolve method getApplicationContext
it appear that you did not inflate the view correctly, change your code to be something like this :
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.your_fragment, container, false);
mButton = (Button) view.findViewById(R.id.mButton );
list_content = (ListView) view.findViewById(R.id.list_content);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
return view;
}
and you should use 'getActivity()' method for context not 'This' .
You can find other view's Id's in your fragment like this.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.your_layout,container,false);
tabLayout = (TabLayout)view.findViewById(R.id.tabs);
return view;
}
When you inflate the view on the oncreateview make a view field like this :
View view = inflater.inflate(R.layout..., container, false);
and return with this view.
After that with this variable you can reach the findViewById, like
view.findViewById
Instead of getApplicationContext you can use getContext in fragment.
Good luck.

getting force close when using findviewbyId()

I'm starting to learn android app development and currently practicing with simple apps. I'm writing this app that includes a listview and i want to fill it with fake data but, when i use findViewbyId() in my code the app gives me force close BUT when i set the content view to my fragment instead of activity_main i get no force close, but the app shows me an empty list.
This is my code :
package com.example.karen.please;
public class MainActivityFragment extends Fragment {
private ArrayAdapter<String> mForecastAdapter;
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String[] forecastArray =
{
"sunny",
"cloudy",
"asteroids",
"rainy",
"sunny"
};
List<String> weekforecast = new ArrayList<String>(Arrays.asList(forecastArray));
mForecastAdapter =
new ArrayAdapter<String>(
getActivity(),
R.layout.list_item_forecast,
R.id.list_item_forecast_textview,
weekforecast
);
ListView mylistview = (ListView)container.findViewById(R.id.listview_forecast); //screws upp in this line
mylistview.setAdapter(mForecastAdapter);
return inflater.inflate(R.layout.fragment_main, container, true);
}}
Any help would be appreciated.
You're trying to find a view before you inflate your layout... Try inflating at the top of your method, like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_main, container, true);
<all the other init code you have>
return myView;
}
First you need inflate your layout...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
...
ListView mylistview = (ListView)rootView.findViewById(R.id.listview_forecast);
...
Before using findViewById you should Create a View variable, use the inflate.. line, use findViewById on the View variable you created, and then return that.
This is what your code should look like:
package com.example.karen.please;
public class MainActivityFragment extends Fragment {
private ArrayAdapter<String> mForecastAdapter;
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Instead of inflate and return instantly, store it in a variable,
// Then return at the end of the method.
View view = inflater.inflate(R.layout.fragment_main, container, true);
[...]
// Here, use findViewById on the View you have just inflated.
ListView mylistview = (ListView) view.findViewById(R.id.listview_forecast); //screws upp in this line
mylistview.setAdapter(mForecastAdapter);
// Return the view you created on the beginning.
return view;
}}
You should start with a proper tutorial not chaotically adding code that you don't understand. Start reading here:
Creating and Using Fragments
After you understood how it goes then you will see that first you need to inflate the layout that contains the stuff you want to find by id and then by using the view(that defines the layout) you can find the desired view(listview, etc).
ListView my listview = (ListView).findViewById(R.id.listview_forcast);
I think this is how it should be, no container in the code

Android-add value to a listview in a fragment via edittext from another fragment

i got a problem here. As the title said, i want to update a listview in a fragment adding a value from an edittext of another fragment. My main activity is a navigation drawer. My fragment with the listview is the Fragment_hotels and the other fragment witch contains the edittext is the FragmentAddHotel. I want to add in the listview (with the hotels) a new hotel.
Can someone explain how to do that?
Code given below:
Fragment_hotels:
public class Fragment_hotels extends Fragment {
public static boolean flag=false;
public void Add(){
Target.add("Hotel");
Target.add("Hotel1");
Target.add("Hotel2");
}
static ArrayList<String> Target = new ArrayList<String>();
#Override
public View onCreateView(
LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState){
View view = inflater.inflate(R.layout.fragment_hotels, container,false);
ListView listView = (ListView) view.findViewById(R.id.list);
if (flag==false){
this.Add();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),R.layout.mytextview,R.id.tv, Target);
adapter.setNotifyOnChange(true);
// Assign adapter to ListView
listView.setAdapter(adapter);
return view;
}
}
And FragmentAddHotel:
public class FragmentAddHotel extends Fragment {
public View onCreateView(
LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_add_hotel, container, false);
return rootView;
}
}
I got an edittext and a button on my FragmentAddHotel layout.
How can i get the value from edittext and add it on the listview?
Sorry if a similar question has already been answered but i am junior programmer.
Tnx in advance :)
To update view in class from another one you can use EventBus library here is the link
Just register you first class by adding:
EventBus.getDefault().register(this); //in your listener class that contains the listview at onCreate method.
Also implement your receiver method:
public void onEventMainThread(String hotelName) {
// Add the hotelName in your Target array list and then notify your adapter by adapter.notifyDataSetChanged();
}
To send data from your fragment just use :
EventBus.getDefault().post("edittextvalue");
Also don't forget to call :
EventBus.getDefault().unregister(this); // In your listener class onDestroy() method.
In YourActivity:
Fragment_hotels frag_hotels;
void addItem(String item){
frag_hotels.addItemToList(item);
}
Fragment_hotels:
List<String> hotelList;
ArrayAdapter<String> adapter;
void addItemToList(String item){
hotelList.add(item);
adapter.notifyDataSetChanged();
}
In FragmentAddHotel:
// you should call whenever adding is need in fragment
((YourActivity)getActivity()).addItem("Your Item");
Through YourActivity, you can communicate each fragment.

Android ListView in Fragment

I am trying to create a list of items which contains an image and some description for the image in each individual. After which, the list will be place in a fragment inside the application. Can anyone guide me to create it? I am not too sure how can I do it without the ListActivity.
It seems like your Fragment should subclass ListFragment (not ListActivity). onCreateView() from ListFragment will return a ListView you can then populate.
Here's more information on populating lists from the developer guide: Hello, ListView
Here's a code snippet to help you display ListView in a fragment.:
public class MessagesFragment extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_messages, container,
false);
String[] values = new String[] { "Message1", "Message2", "Message3" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
return rootView;
}
}
And, this is how the xml would look like:
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
If you do not use 'list' as ID or do not include a ListView into your layout, the application crashes once you try to display the activity or the fragment.
Reference: http://www.vogella.com/tutorials/AndroidListView/article.html#listfragments

Categories

Resources