Adding items on a spinner using a cutom function in a fragment - android

How do i add items to a spinner in a fragment using a custom method since i have many spinners and setting each on the create view makes the code have unprofessional looking
This is what i have tried but returns an error
I had also declared the provincespinner
private Spinner provincespinner, districtspinner;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_basicinfo, container, false);
addItemsOnProvinceSpinner(rootView); //this is what i would like to add items
...i have other methods to add other spinners here
return rootView;
}
This is the method that should add but returns an error
public void addItemsOnProvinceSpinner(View rootview) {
provincespinner = (Spinner) rootview.findViewById(R.id.fivms_farmerprovince);
List<String> list = new ArrayList<String>();
list.add("list 1");
list.add("list 2");
list.add("list 3");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, list); //This returns an error
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
provincespinner.setAdapter(dataAdapter);
}
How do i go about this

Modify your line like this:
ArrayAdapter<String> dataAdapter = new
ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item, list);
the first parameter is context and you are passing this which works for activity

Related

basic List View - Find by ID not working

i am trying to get a list view working in android studio.
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
populateListView();
return inflater.inflate(R.layout.stand1,container,false);
}
private void populateListView() {
String[] pair = {"Pair1","Pair2","Pair3","Pair4","Pair5"};
//build adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.stand1,pair);
//populate
ListView list = (ListView) findViewById(R.id.Stand1list);
list.setAdapter(adapter);
}}
The errors i am getting are
Error:(31, 40) error: no suitable constructor found for ArrayAdapter(Stand1,int,String[])
constructor ArrayAdapter.ArrayAdapter(Context,int,int) is not applicable
(argument mismatch; Stand1 cannot be converted to Context)
constructor ArrayAdapter.ArrayAdapter(Context,int,String[]) is not applicable
(argument mismatch; Stand1 cannot be converted to Context)
constructor ArrayAdapter.ArrayAdapter(Context,int,List<String>) is not applicable
(argument mismatch; Stand1 cannot be converted to Context)
Error:(34, 36) error: cannot find symbol method findViewById(int)
stand1 is an xml file, Stand1List is the listview id inside the stand1.xml
I know its something simple , but for the life of me i dont know what...
For references Stand1.java is java file which is a fragment inside the activity_main. It is being called by a nav drawer.
Update:
Thanks to Jedil Answer, i have it kinda working. However i have gotten an error when i load the fragment saying text view needs an ID.
I have no put a textview inside the stand1.xml Below.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/Stand1list">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tex1"
/>
</ListView>
</FrameLayout>
And now i am getting error
java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView
change your code to this instead:
View view = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.stand1,container,false);
populateListView(view);
return view;
}
private void populateListView(View mView) {
String[] pair = {"Pair1","Pair2","Pair3","Pair4","Pair5"};
//build adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), R.layout.stand1,pair);
//populate
ListView list = (ListView) mView.findViewById(R.id.Stand1list);
list.setAdapter(adapter);
}}
ListView listview; // define this on class level
View view = inflater.inflate(R.layout.stand1,container,false);
listview = view.findViewById(R.id.Stand1list);
populateListView();
retur view ;
And In populateListView() you set adapter in this way
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.stand1,pair);
You are calling populateListView() too early, because your view isn't created yet.
Try use populateListView() in
public void onViewCreated (View view, Bundle savedInstanceState)
Declare the ListView as a member variable of the fragment:
ListView list; // your ListView
And instead of passing this to your ArrayAdapter, you need to pass getActivity(), the host activity's context.
And finally, initialize the listView inside the onCreateView method.
list = (ListView) findViewById(R.id.Stand1list);
CODE:
ListView list; // your ListView
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.stand1,container,false);
list = (ListView) view.findViewById(R.id.Stand1list);
populateListView();
}
private void populateListView(View mView) {
String[] pair = {"Pair1","Pair2","Pair3","Pair4","Pair5"};
//build adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.stand1,pair);
list.setAdapter(adapter);
}
Your code is a fragment implementation code.
First error is about that ArrayAdapter needs Context as first argument.
So this in that place of code meansfragment object, but you need Context which could be Activity so instead of using this use getActivity() in those places
ArrayAdapter<String>(getActivity(), R.layout.stand1,pair);
and
ListView list = (ListView) getActivity().findViewById(R.id.Stand1list);
So how code should look like :
ListView mList;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.stand1,container,false);
mList = (ListView) root.findViewById(R.id.Stand1list);
return root;
}
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
populateListView();
}
private void populateListView() {
String[] pair = {"Pair1","Pair2","Pair3","Pair4","Pair5"};
//build adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.stand1,pair);
mList.setAdapter(adapter);
}}

ArrayAdaptor constructor not being found

I am working to display a list of all devices that have been connected to an Android phone. I would really like to keep using the fragments to help with easy navigation. I am getting an error on the ArrayAdapter adapter1 code that states Cannot resolve constructor 'ArrayAdapter(com.henryjarend.test.Connect2, int, java.util.List<java.lang.String>)'
I have looked at the constructor on the android developer APIs and it seems like it should be working.
Here is the code:
public class Connect2 extends ListFragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.connect2, container, false);
}
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
BluetoothAdapter myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = myBluetoothAdapter.getBondedDevices();
List<String> previousDevices = new ArrayList<String>();
for(BluetoothDevice bt : pairedDevices){
previousDevices.add(bt.getName());
}
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, R.layout.connect2, previousDevices);
//setListAdapter(new ArrayAdapter<String>(this, android.R.id.list, previousDevices));
}
}
the commented out section was another example I had found online but it had the same issue that the uncommented one is having.
The problem :
ArrayAdapter<String> adapter1 =
new ArrayAdapter<String>(this, R.layout.connect2, previousDevices)
this here is a ListFragment, get activity of this fragment for the context.
Solution :
ArrayAdapter<String> adapter1 =
new ArrayAdapter<String>(getActivity(), R.layout.connect2, previousDevices)

Updating fragment view after setting listAdapter

I am converting an existing activity (SherlockActivity) into fragment (SherlockListFragment) in order to use tabs.
The fragment returns a onCreateView when created and is using the following code.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/** Creating array adapter to set data in listview */
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getBaseContext(), android.R.layout.simple_list_item_multiple_choice, android_versions);
/** Setting the array adapter to the listview */
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
That works fine but as I was doing in my activity I want to update the list view with my own content after I finish fetching it from the server.
ListView listContent = (ListView) getView().findViewById(R.id.contentlist);
listContent.setAdapter(myAdapter);
Whatever I have researched so far, I am fetching the listview through activity and setting my adapter to it but that is having no effect on fragment view and it remains the same.
Question is: How can I update listView from outside onCreateView?
First, make your listview a global var. Then set its value on the onCreateView function:
ListView list;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_placelist, container, false);
list = rootView.findViewById(/*your id*/)
/** Creating array adapter to set data in listview */
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getBaseContext(), android.R.layout.simple_list_item_multiple_choice, android_versions);
/** Setting the array adapter to the listview */
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
//change your listview content here when refresh or something else
public void updateListView(){
List l = /*fetch new data from server*/
listAdapter.addAll(l);
listAdapter.notifyDataSetChanged();
}
ListView list;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_placelist, container, false);
list = rootView.findViewById(/*your id*/)
/** Creating array adapter to set data in listview */
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getBaseContext(), android.R.layout.simple_list_item_multiple_choice, android_versions);
/** Setting the array adapter to the listview */
setListAdapter(adapter);
return rootView;
}
from here android versions must be a arraylist or string array or hashmap

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

How to set ArrayAdapter for spinner in Fragment

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

Categories

Resources