How to set ArrayAdapter for spinner in Fragment - android

I am trying to add items to spinner in fragment. But i am having problem with the context. Because in fragment there is no context. Here how i am doing
public class DetailFrag extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View scrollView = inflater.inflate(R.layout.myscrollview , container, false);
LinearLayout linearLayout = (LinearLayout) scrollView.findViewById(R.id.mylayout1);
for (int i=0; i<questionList.size(); i++) {
View verticalLinearLayout = inflater.inflate(R.layout.mylistrow, null);
View horizontalLInearLaoyout = verticalLinearLayout.findViewById(R.id.questionRow);
TextView tv = (TextView) horizontalLInearLaoyout.findViewById(R.id.question);
Spinner spinner = (Spinner) horizontalLInearLaoyout.findViewById(R.id.spinner);
//Problem: how to define this in fragment createFromResource(this,...)
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.options_array, android.R.layout.simple_spinner_item);
EditText editText = (EditText) verticalLinearLayout.findViewById(R.id.txtMultiLine);
String question = questionList.get(i).question;
tv.setId(i);
tv.setText(i + question);
spinner.setId(i);
editText.setId(i);
linearLayout.addView(verticalLinearLayout);
}
return scrollView;
} //end of onCreateView()
} //end of class DetailFrag

In fragments, context is not available the way you expected in your code. Instead of this, use the following:
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
getActivity().getBaseContext(),
R.array.options_array,
android.R.layout.simple_spinner_item);

Since there we are in a Fragment,'this', won't work thus:
Using getActivity().getBaseContext() should be used to replace 'this';
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(getActivity().getBaseContext(),
android.R.layout.simple_spinner_dropdown_item,
listItems);
Note on older versions of Android there is getContext() which will return context of the fragment as well, but for new versions it might not return context. Thus using getActivity() you are turned a Activity which is a context.
We use getActivity() which gets the current activity you are in followed by getBaseContext() since there can be multiple Context initiated in the Activity. We want to get the one that the Activity itself uses.

do something like :
private Context myContext = null;
public DetailFrag(Context ctx){
myContext = ctx;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//...
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
myContext, R.array.options_array, android.R.layout.simple_spinner_item);
//
}

Related

Spinner not filled with ArrayAdapter

So my spinner isn't being filled programatically:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first_boot__language_selection, container, false);
setupSpinner(view, R.id.firstLanguageSpinner, R.array.languagesSpinner);
setupSpinner(view, R.id.secondLanguageSpinner, R.array.languagesSpinner);
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_first_boot__language_selection, container, false);
}
private void setupSpinner(View view, int spinnerResourceId, int arrayResourceId) {
Spinner spinner = view.findViewById(spinnerResourceId);
spinner.setSelection(1);
//Adapts strings into CharSequence.
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this.getContext(), arrayResourceId, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
However I cannot for the life of me figure out why not? I would fill it via XML, however this code doesn't include other functions that I had added. For instance, in setupSpinner, I had added the onClickListener event, which wasn't working.
In onCreateView you should be using return view;, not return inflater.inflate... What you are doing is inflating a second copy of the fragment, which is not initialized with spinner data.

Error Image listview fragment

enter image description hereBelow is the coding i have and it seems i have problem on the
AgentAdapter adapter = new AgentAdapter(getActivity(), R.layout.list_agent, member_names, profile_pics);
How do i use image and text together for the list adapter i have in my fragment? Please help.
public class AgentFragment extends Fragment{
String[] member_names;
TypedArray profile_pics;
ListView mylistview;
String[] agentname={"Robert","Shanni","Rachel","Mady","Nikhil"};
Integer [] imgid = {R.drawable.robert,R.drawable.shanni,R.drawable.rachael,R.drawable.maddy_pic,R.drawable.nikhil_pic};
public AgentFragment(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_layout1, null);
setupList(view);
return view;
}
private void setupList(View view){
AgentAdapter adapter = new AgentAdapter(getActivity(), R.layout.list_agent, member_names, profile_pics);
mylistview = (ListView) view.findViewById(R.id.listView);
mylistview.setAdapter(adapter);
}
}
Since its possible that the fragment has not been placed in any activity at runtime you can afford for this by changing the getActivity() to be the context from the view parameter:
private void setupList(View view){
AgentAdapter adapter = new AgentAdapter(view.getContext(), R.layout.list_agent, member_names, profile_pics);
mylistview = (ListView) view.findViewById(R.id.listView);
mylistview.setAdapter(adapter);
}

Android add view to fragment and bind adapters to views

Hello I'm playing around with fragments as of now, and I can't seem to find a solution to this issue..
This is what I have tried so far:
FragmentReceivingStocksHeader.class
public class FragmentReceivingStocksHeader extends Fragment {
EditText etVanTransferDocument, etDocumentNumber;
Spinner spLocationFrom, spLocationTo;
Button btExit, btProcess;
ArrayAdapter<String> adapterFrom, adapterTo;
String[] locationsFromArray, locationsToArray;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
initControls();
View rootView =
inflater.inflate(R.layout.fragment_receivingstocks_transactionheader, container, false);
return rootView;
}
private void initControls() {
// TODO Auto-generated method stub
spLocationFrom = (Spinner) findViewById (R.id.spLocationFrom);
spLocationFrom.setEnabled(false);
spLocationTo = (Spinner) findViewById (R.id.spLocationTo);
spLocationTo.setEnabled(false);
locationsFromArray = getResources().getStringArray(R.array.locations);
locationsToArray = getResources().getStringArray(R.array.locationsto);
adapterFrom = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, locationsFromArray);
adapterTo = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, locationsToArray);
spLocationFrom.setAdapter(adapterFrom);
spLocationFrom.setSelection(1);
spLocationTo.setAdapter(adapterTo);
spLocationTo.setSelection(0);
}
But I have errors on this line:
spLocationFrom = (Spinner) findViewById (R.id.spLocationFrom);
Error Message:
The method findViewById(int) is undefined for the type FragmentReceivingStocksHeader
And also these lines:
adapterFrom = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, locationsFromArray);
adapterTo = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, locationsToArray);
Error Message:
The constructor ArrayAdapter<String>(FragmentReceivingStocksHeader, int, String[]) is undefined
What am I doing wrong in here? I need your help guys. Thanks.
In your initControls method, make the following modifications :
spLocationFrom = (Spinner) view.findViewById (R.id.spLocationFrom);
spLocationTo = (Spinner) view.findViewById (R.id.spLocationTo);
and
adapterFrom = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item, locationsFromArray);
adapterTo = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item, locationsToArray);
Explanation : findViewById is not available in Fragment like it is in Activity, so you need to use the View.findViewById method.
And the constructor or ArrayAdapter takes a Context as first argument, so Activity works but not Fragment.
The problem is, that Fragment class doesnt have method like findViewById, like Activity does. You need to use your inflated rootView.findViewById.
As for your adapters, similarly, the constructor doesnt accept Fragment type, but Context. Activity class extends Context, and you can access your activity from Fragment with getActivity() method.
See your code updated below:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView =
inflater.inflate(R.layout.fragment_receivingstocks_transactionheader, container, false);
initControls(rootView);
return rootView;
}
private void initControls(View view) {
// TODO Auto-generated method stub
spLocationFrom = (Spinner) view.findViewById (R.id.spLocationFrom);
spLocationFrom.setEnabled(false);
spLocationTo = (Spinner) view.findViewById (R.id.spLocationTo);
spLocationTo.setEnabled(false);
locationsFromArray = getResources().getStringArray(R.array.locations);
locationsToArray = getResources().getStringArray(R.array.locationsto);
adapterFrom = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item, locationsFromArray);
adapterTo = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item, locationsToArray);
spLocationFrom.setAdapter(adapterFrom);
spLocationFrom.setSelection(1);
spLocationTo.setAdapter(adapterTo);
spLocationTo.setSelection(0);
}

Spinner values get doubled every time I click on the activity

I am using a fragment activites. One of my activity has a spinner. I set its adapter. The problem is whenever I switch to that activity, spinner values increase. It actually adds the the same values into the spinner without removing the previous ones. How to solve it? my code is following:
public class AddPackageFragment extends Fragment {
View rootView;
EditText packageName;
EditText packageNumber;
Spinner network;
CheckBox sim1;
CheckBox sim2;
RadioGroup type;
RadioGroup through;
Button addPackage;
Button actDetails;
ArrayList<String> networks = new ArrayList<String>();
ArrayAdapter<String> adapter;
Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.add_package, container, false);
initializeViews();
setNetworks();
setSpinner();
return rootView;
}
void initializeViews() {
packageName = (EditText)rootView.findViewById(R.id.pName);
packageNumber = (EditText)rootView.findViewById(R.id.pNumber);
network = (Spinner)rootView.findViewById(R.id.networkS);
sim1 = (CheckBox)rootView.findViewById(R.id.sim1);
sim2 = (CheckBox)rootView.findViewById(R.id.sim2);
type = (RadioGroup)rootView.findViewById(R.id.typeGroup);
through = (RadioGroup)rootView.findViewById(R.id.throughGroup);
addPackage = (Button)rootView.findViewById(R.id.addPackage);
actDetails = (Button)rootView.findViewById(R.id.activationDetails);
context = getActivity().getApplicationContext();
addPackage.setActivated(false);
actDetails.setActivated(false);
}
void setNetworks() {
networks.add("Mobilink");
networks.add("Telenor");
networks.add("Ufone");
networks.add("Warid");
networks.add("Zong");
networks.add("Add New");
}
void setSpinner() {
adapter = new ArrayAdapter<String>(context, R.layout.spinner_item, networks);
network.setAdapter(null);
network.setAdapter(adapter);
}
}
Try this:
void setNetworks() {
networks.clear()
networks.add("Mobilink");
networks.add("Telenor");
networks.add("Ufone");
networks.add("Warid");
networks.add("Zong");
networks.add("Add New");
}
I think it's because your array not cleared, not the spinner adapter.
To elaborate on #Dimmerg
Based on the Fragment lifecycle, your onCreateView will get called more than one time. So you have to take that into consideration and clear values (or Lists) accordingly.

The constructor ArrayAdapter<String>(LayoutNext, int, String[]) is undefined

I try to implement the items to a Spinner from a android.support.v4.app.Fragment class. I always get the compiler Error
The constructor ArrayAdapter(LayoutNext, int, String[]) is undefined
How can I fix this?
Here is the code:
public class LayoutNext extends Fragment
implements OnClickListener,OnItemSelectedListener{
TimePicker timepicker;
private Spinner spinner_next;
public ArrayAdapter<String> adapter;
public static Fragment newInstance(Context context) {
LayoutNext f = new LayoutNext();
return f;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.layout_next, null);
timepicker = (TimePicker) root.findViewById(R.id.timePicker1);
timepicker.setIs24HourView(true);
timepicker.setCurrentHour(0);
timepicker.setCurrentMinute(0);
String[] items_next = { "Next", "From to"};
spinner_next = (Spinner) root.findViewById(R.id.sp_next);
spinner_next.setOnItemSelectedListener(this);
// Here I get the error
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_spinner_item,
items_next);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_next.setAdapter(adapter);
return root;
}
Unlike Activities, Fragments are not subclasses of Context so you cannot use this where a Context is required. Simply use getActivity() instead.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getActivity(),
android.R.layout.simple_spinner_item,
items_next);

Categories

Resources