extract value from spinner and use it to calculations -- NullPointerException - java

I want to use the "value" from the spinner.
When the user makes the choice i want to use that value in order to do some calculations.
My problem is :
1) How to get properly the value (item).I am using sth like "item.MyOnItemSelectedListener ==0".
2) What the value should be?For example ,above i have ==0 .This means the first choice from the spinner list?
The code:
public class number_cores extends Activity implements OnClickListener {
..
final Spinner spinner = (Spinner) findViewById(R.id.spinner);
...
public void onCreate(Bundle savedInstanceState) {
....
//spinner-drop_list
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.init_or_final, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
}
...
public void cores_func(){
...
double fcores=0;
MyOnItemSelectedListener obj=new MyOnItemSelectedListener();
if ( obj.getPosition()==0) fcores=initcores*Math.exp(-l*ttime);
else if (obj.getPosition()==1) fcores=initcores/Math.exp(-l*ttime);
..}
//spinner class
public class MyOnItemSelectedListener implements OnItemSelectedListener {
private int position;
public int getPosition() {return position;}
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
position=pos;
}
public void onNothingSelected(AdapterView <?> parent) {
// Do nothing.
}
}
Thanks!

Right now all you are doing is assigning the Object item the value of the selected item in the spinner. You aren't saving that value anywhere you can access it.
To fix this, in your OnItemSelectedListener save the selected value or position in a field. Access it through a getter method in your listener that returns the value. In the onItemSelected method you would set the value each time the user changes the spinner's value. In the Activity, access the saved value through the listener via the getter method.
Example:
If you wanted to get the position of the selected item, add private int position; and public int getPosition() {return position;} as a field and method (respectively) in the listener class, and in the onItemSelected method position = pos; to save the value. It is a similar idea to save the object if you want that. In your application, listenerName.getPosition() == 0 would be true if the first thing in the list was the selected item, so you can do logic with it.

Related

Identify a button click on list view android

I have created a ListView using a custom adapter that extends ArrayAdapter<String>. I need to add the item name to an ArrayList when it clicks on the + button.
You can do it exactly as usual (like in MainActivity), just link it in GetView(...)
Inside your ArrayAdapter.java , add this:
private OnItemClickListener mListener;
public interface OnItemClickListener
{
void onAddClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener)
{
mListener = listener;
}
Inside your Holder Function on same file, make this:
AddButtonVariable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null)
{
int position = getAdapterPosition();
if(position != ListView.NO_POSITION)
{
listener.onAddClick(position);
}
}
}
});
Inside in your onResponse function of Activity.java file add this, after setAdapter:
listAdapter.setOnItemClickListener(new ArrayAdapter.OnItemClickListener() {
#Override
public void onAddClick(int position){
functiontoAdd(String.valueOf(position));
}
});
Now, at last, inside your Activity.Java file, at the end (before closing bracket of class), add this:
private void functiontoAdd(String position)
{
// rest of the code to add item in cart
}
Look, it is simpler with using Recycler view instead of list view. But it is ok if you already created.
listview.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long id)
{
//I am assuming the ArrayAdapter is having list of dish name as string if the list is of Custom class please change the below code as per it.
String dish = (String)adapter.getItemAtPosition(position);
}
});
adapter AdapterView: The AdapterView where the click happened.
view View: The view within the AdapterView that was clicked (this will be a view provided by the adapter)
position int: The position of the view in the adapter.
id long: The row id of the item that was clicked.

RecyclerView - findViewHolderForAdapterPosition() returns null for invisible items

I am trying to update all views on RecyclerView item click. I tried findViewHolderForAdapterPosition() to get the ViewHolder but it returns null for invisible items. I understand that the method can return null if view is not yet prepared and it won't be a wise idea to update other invisible lists if the list is huge. However, my list is very small (always less than 10) and I want to get access to views/viewholders upon an item click.
I am using the following code to update the ViewHolders
for (int i = 0; i < itemsList.size(); i++) {
if (i != getAdapterPosition()) {
MyViewHolder temp = (MyViewHolder) recyclerView.findViewHolderForAdapterPosition(i);
if (temp != null) {
//update elements
} else {
Log.i(TAG, "temp is null");
}
}
}
Any help or leads would be appreciated.
I want to get access to views/viewholders upon an item click.
You can simply achieve this functionality by setting onClickListener on any view, inside the onBindViewHolder() method of your adapter.
For dispatching the click event on an item to an activity or fragment for handling :
1- In your adapter class, define an interface called OnItemClickListener :
public interface OnItemClickListener {
void onItemClicked(int position, AnyOtherDataYouWant data)
}
2- Make your activity or fragment implement this interface
public MyActivity extends AppCompatActivity implements MyAdapter.OnItemClickListener
3- Pass a reference of type OnItemClickListener interface to the constructor of your adapter and save it in an field, called listListener .
4- In the onBindViewHolder of your adapter, on the view you want like a button or a textview :
holder.myview.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
listListener.onItemClicked(position, AnyDataYouWant data) ;
}
}) ;

Problems with global variable in inner OnItemClickListener class

I have an android fragment, that has a listview. for that listview I implemented an inner OnItemClickListener class.
When there's a click, I save the selection in a global variable called SelectedIndex.
If I click again on that list, I can see the previous selection correctly, So its saving the state on the global variable correctly.
The problem is when I try to access to that same global variable from another inner class, for example, one class used for listen to clicks on a button. Is always showing the value I used for initialize the varialbe (-1).
The code of the fragment:
/**
* A placeholder fragment containing the view for the recentCalls list
*/
public class RecentCallsFragment extends Fragment {
private Cursor cursorAllRows;
private RecentCallsTable rcTable;
private ListView list;
private RecentCallsAdapter adapter;
Button btnDelete, btnCreditRequest, btnCreditBlock, btnSendTo;
int selectedIndex; //this is the global variable that I am using.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rcTable = new RecentCallsTable(getActivity());
cursorAllRows = rcTable.getRecentCallsCursor();
adapter = new RecentCallsAdapter(getActivity(), cursorAllRows);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
list = (ListView) view.findViewById(R.id.listViewMain);
btnDelete = (Button) getActivity().findViewById(R.id.buttonDelete);
btnCreditRequest = (Button) getActivity().findViewById(R.id.buttonCr);
btnCreditBlock = (Button) getActivity().findViewById(R.id.buttonCRD);
list.setAdapter(adapter);
list.setOnItemClickListener(new ItemClickHandler()); //Add the inner ItemClickLister
btnSendTo = (Button) getActivity().findViewById(R.id.buttonSendTo);
btnSendTo.setOnClickListener(new DebugOnClick());//here I add the inner clicklister
return view;
}
/**
* Class that handles the one click action on the list
*/
public class ItemClickHandler implements AdapterView.OnItemClickListener{
//when there's one fast click, keep the selection on the item or remove it if already has it
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
int prevSelection = adapter.getSelectedIndex();
Toast.makeText(getActivity(), Integer.toString(selectedIndex), Toast.LENGTH_SHORT).show();
int newSelection = position;
if(prevSelection == position){
newSelection = -1;
}
selectedIndex = newSelection; //here I change the value of the global variable
adapter.setSelectedIndex(newSelection);
adapter.notifyDataSetChanged();
}
}
public class DebugOnClick implements View.OnClickListener{
public DebugOnClick(){
}
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), Integer.toString(selectedIndex), Toast.LENGTH_SHORT).show(); //here I show the value of the global variable and is always -1
}
}
}
Which may be the problem?
There is one possibility that comes into my mind. When you have an inner class instantiated it implicitly binds with an instance of the hosting class (as if it were a reference of the hosting class). So I assume that the inner classes that you use are each linked with a different instance of the hosted class and thus using a different selectedIndex. Your global variable is not really global, its an instance variable.
I just found the problem. The buttons are in the main activity, so I just moved the global variable to the main Activity and started to manipulate it from the fragments like this:
MainActivity ma = (MainActivity) getActivity();
ma.rcSelected = newSelection;

how to set a text views text to an integer value of an object that was created from another class

the title is a bit confusing sorry about that i didnt know how to put it in words properly. I have a listView that uses an Adapter that i created myself. When the first row of the listView is pressed I have made it so it creates a new object from class called Ship that has 3 integer values. Below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hangar);
ListAdapter adapter = new HangarAdapter(this, ship);
hangarList.setAdapter(adapter);
hangarList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Intent sendListEvents = new Intent();
if(position == 0)
{
Ship ship1 = new Ship();
ship1.setAddAmount(50);
ship1.setAddTime(5000);
ship1.setAddSpend(1000);
ship1.shipAdd();
}
}
}
In my adapter i have a textView called TextView2 and I want to set the text of it to ship1's value called addSpend. How do i do that.
if (position == 0) {
theImageView.setImageResource(R.drawable.planet);
TextView2.setText("This is where I want ship1's addSpend value to be displayed")
}
Well if I am correct then you have in the HangarAdapter class the object this (which references to the Activity in which you are right now: ListAdapter adapter = new HangarAdapter(this, ship);). Save this object to an variable (I call it MainActivity) in the HangarAdapter class .
Now you could just say in the HangarAdapter class: MainActivity.findViewById("TextBoxID").setText("MUHAHAHAH")

Unable to access variable inside listener

I have a listener excerpt below which contains the variable degree.
public class CustomOnItemSelectedListener implements AdapterView.OnItemSelectedListener {
//Define Components
public EditText text;
public Spinner spinner1;
//Define Variables
public String degree;
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
//Set the selected item on spinner1 to the variable tempValue
String tempValue = spinner1.getSelectedItem().toString();
degree = "jobby";
}
I am trying to access that variable within my ViewPager adapter like so:
public class MyPagerAdapter extends FragmentPagerAdapter {
public CustomOnItemSelectedListener selectedListener;
[...]
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return resultFragment.newInstance(selectedListener.degree);
case 1: return resultFragment.newInstance("resultFragment, Instance 2");
default: return resultFragment.newInstance("resultFragment, Default");
}
}
[...]
}
And in my MainActivity
protected void onCreate(Bundle savedInstanceState) {
[...]
myPager = new MyPagerAdapter(getSupportFragmentManager());
selectedListener = new CustomOnItemSelectedListener();
addListenerOnSpinnerItemSelection();
myPager.selectedListener = selectedListener;
}
The issue I am having is that I am unable to access the variable of degree. If I set the value of the variable at the top of the listener class like so
public String degree = "jobby";
Then I can access the variable.
I am trying to write an if statement within the listener, and depending on which item of the spinner is selected, the variable changes.
How can I access the variable within the listener class?
I think it's because you need initialize the variable, try this:
public String degree = null;
And make sure when you use the variable it's with the correct value, to try avoid NullPointerExceptions.
In CustomOnItemSelectedListener#onItemSelected the fragment needs to be replaced using the Activity's FragmentManager.
Refer to the Fragment example code (scroll down to the showDetails() method). However, instead of FragmentManager#findFragmentById you should use FragmentManager#findFragmentByTag.
Perhaps something like this:
FragmentManager fragManager = getFragmentManager();
FragmentTransaction xact = fragManager.beginTransaction();
ResultFragment resultFragment = (ResultFragment)fragManager.findFragmentByTag(selectedListener.degree);
if(resultFragment == null) {
mList = resultFragment.newInstance(selectedListener.degree);
xact.add(R.id.view_container, resultFragment, selectedListener.degree);
}
xact.commit();
Be careful, though, if degree varies wildly then this would result in many Fragments contained in the FragmentManger. In this case you should remove the unused Fragments as needed.

Categories