In my application I have fragment which contains spinner, button, editText and multiple TextViews. This is my code for getting users selected item and displaying it:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Get position
int index = productSpinner.getSelectedItemPosition();
int[] tableSpoonList = getResources().getIntArray(R.array.tableSpoon);
int[] glassList = getResources().getIntArray(R.array.glass);
int[] teaSpoonList = getResources().getIntArray(R.array.teaSpoon);
// Set the texts and defaults
if (glassList[index] == 0) {
typeGlass.setVisibility(View.INVISIBLE);
} else {
typeGlass.setText(getString(R.string.glass) + glassList[index] + getString(R.string.grams));
typeGlass.setVisibility(View.VISIBLE);
}
if (tableSpoonList[index] == 0) {
typeTablespoon.setVisibility(View.INVISIBLE);
} else {
typeTablespoon.setText(getString(R.string.table_spoon) + tableSpoonList[index] + getString(R.string.grams));
typeTablespoon.setVisibility(View.VISIBLE);
}
if (teaSpoonList[index] == 0) {
typeTeaspoon.setVisibility(View.INVISIBLE);
} else {
typeTeaspoon.setText(getString(R.string.tea_spoon) + teaSpoonList[index] + getString(R.string.grams));
typeTeaspoon.setVisibility(View.VISIBLE);
}
}
As I mentioned, I have an editText and a button. I want the user to enter a number in editText and do little calculations with the values then display it.
I came up with solution, setting buttons onCLick called convert:
public void convert (View view) {
int userInput = Integer.parseInt(valueInput.getText().toString());
if (userInput == 0) {
Toast.makeText(getContext(), "Enter the value!", Toast.LENGTH_SHORT).show();
} else {
double customTableSpoon = (1/tableSpoonList[index]) * userInput;
typeTablespoon.setText(Double.toString(customTableSpoon));
}
}
But as you can see, I cant get from
double customTableSpoon = (1/tableSpoonList[index]) * userInput;
tableSpoonlist[index], because it is defined in spinners onItemSelected. However, If I define it outside before convert method
//Get position
int index = productSpinner.getSelectedItemPosition();
int[] tableSpoonList = getResources().getIntArray(R.array.tableSpoon);
int[] glassList = getResources().getIntArray(R.array.glass);
int[] teaSpoonList = getResources().getIntArray(R.array.teaSpoon);
I get crash when switching to that fragment, because
int index = productSpinner.getSelectedItemPosition();
returns null.
And I cant implement onClick in fragment, because I'm already implementing AdapterView.OnItemSelectedListener.
Also, my spinner is created onCreateView:
//Create spinner
productSpinner = (Spinner) view.findViewById(R.id.productSpinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(), R.array.products_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
productSpinner.setAdapter(adapter);
productSpinner.setOnItemSelectedListener(this);
How can I get the spinners selected item so the user can "edit" it?
Related
I've written a game where the user inputs the number of player and every player gets an own tab with an empty table.
Therefore I used a PagerAdapterClass (extends FragmentStatePagerAdapter) and a viewpager.
So every player has the same fragmentView.
Now the user can put variables into the table, bu everytime I switch between the tabs, the input gets lost.
Well, i 'fixed' that problem by adding this to my pageradapter:
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
}
But it's more stopping the viewpager from destroying than actually saving the data.
My main goal is to really save that stuff in that table.
I already tried https://stackoverflow.com/a/17135346/11956040 but i cannot get mContent because i cannot get the reference of the fragment, because all fragments are not created on their own but all at the same time (or something like that).
I also don't know how to set a Tag.
This way: https://stackoverflow.com/a/18993042/11956040
doesn't work for me.
MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Toolbar toolbar = findViewById(R.id.toolbar2);
setSupportActionBar(toolbar);
...
//numPlayer = num of tabs
SectionsPagerAdapter adapter = new SectionsPagerAdapter(numPlayer, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(adapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
if(numPlayer >= 5) {
tabs.setTabMode(TabLayout.MODE_SCROLLABLE);
}
}
PagerAdapter:
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
private int tabNum;
public SectionsPagerAdapter(int tabNum, FragmentManager fm) {
super(fm);
this.tabNum = tabNum;
}
#Override
public PlaceholderFragment getItem(int position) {
return PlaceholderFragment.newInstance(position);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
int playerNum = position + 1;
return "Spieler " + playerNum;
}
#Override
public int getCount() {
// Show 2 total pages.
return tabNum;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
}
}
Fragment:
public static PlaceholderFragment newInstance(int index) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle bundle = new Bundle();
bundle.putInt("player", index);
fragment.setArguments(bundle);
return fragment;
}
There must be a solution but I cannot find it or cannot implement it.
Pls help.
Solved my problem this way:
define 2 dimensional ArrayList for rows and columns and counter for columns:
private ArrayList<ArrayList<Integer>> columnArray;
private int column;
onCreateView (for fragments) set column = 0 and add one entry with an empty list to columnArray
and set the first rowList on column index of columnArray:
pointArray.add(column, new ArrayList<Integer>());
final ArrayList<Integer> rowList = pointArray.get(column);
fill the empty rowListwith 0 (maybe it also works in an other way, but I made it this way to have on empty EditTexts a 0 and can easily replace them)
define View.OnFocusChangeListener for all EditTexts like this:
/*I dont know if I could set column final in general,
but you need to set a final int because you call this value in an inner class*/
final int pos = column
for (int i = 0; i <= getEditTexts(pos).size() - 1; i++) {
EditText editTexts = getEditTexts(pos).get(i);
final String editTextsTag = editTexts.getTag().toString();
View.OnFocusChangeListener listener = new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, final boolean b) {
if (view.getTag().toString().equals(editTextsTag) && !b) {
//fills rowList
addEntries(pos, rowList);
//adds rowList to columnArray
columnArray.set(pos, rowList);
//save the columnsArray or use it
saveData(columnArray);
}
}
};
editTexts.setOnFocusChangeListener(listener);
define method which collects data from each cell, depending on column position (pos), add it to rowList
for example:
private void addEntries(int pos, ArrayList<Integer> rowList) {
for(int i = 0; i <= 16; i++) {
//this requires EditText_label, i made them dynamically
String edit_label = "edit_" + pos + i;
EditText editText = table.findViewWithTag(edit_label);
String mEditTextString = editText.getText().toString();
try {
int thisValue = Integer.parseInt(mEditString);
rowList.set(j, thisValue);
} catch (NumberFormatException e) {
//maybe you do not need this, but I need it for something else
int thisValue = 0;
rowList.set(j, thisValue);
}
}
}
define a method for saving the columnArray. I used an interface to give it to parent Activity: Here you can find how I made it
Otherwise you can convert the columnArray to a String and save it in a database.
NOTE
I made it with column value set beacuse I increase the value for every column I add during runtime using a method. If you just have one column, you dont need to set it. Just use 0 instead of pos, column
I am trying to change background color in specific item(s) in a RecycleView.
Because I need to set text too, I have the following code that works fine:
protected void populateViewHolder(RankingViewHolder viewHolder, final Ranking model, int position)
{
final Context mContext = getActivity().getApplicationContext();
viewHolder.txt_name.setText(model.getUserName());
viewHolder.txt_score.setText(String.valueOf(model.getScore()));
viewHolder.txt_class.setText(model.getUser_class());
Picasso.with(mContext).load(model.getAvatarUrl()).error(R.drawable.ic_people_black_24dp).into(viewHolder.personPhoto);
int totalRanking = adapter.getItemCount();
int realRank = totalRanking - viewHolder.getAdapterPosition();
viewHolder.ranknumber.setText("# "+String.valueOf(realRank));
}
This works as I want and realRanktakes the correct values, and the viewHolder.ranknumber.setText("# "+String.valueOf(realRank));
Sets the right text with no problem.
Now I am trying (as I got a number/text result correct, to make an if statement like this:
if(adapter.getItemCount() -viewHolder.getAdapterPosition() == 0)
{
viewHolder.itemView.setBackgroundColor(Color.GREEN);
}
if(adapter.getItemCount() -viewHolder.getAdapterPosition() == 1)
{
viewHolder.itemView.setBackgroundColor(Color.YELLOW);
}
if(adapter.getItemCount() -viewHolder.getAdapterPosition() == 2)
{
viewHolder.itemView.setBackgroundColor(Color.BLUE);
}
(I tried with String.valueOf(realRank)equality, with realRankequality too)
In all cases I have the same result. The color changes as its should at positions 1,2,3 BUT it changes at positions 7,8,9 and 14,15,16 and 21,22,23 etc.
What am I missing here?
public class RankingViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
private ItemClickListener itemClickListener;
public TextView txt_name, txt_score, txt_class, ranknumber;
public ImageView personPhoto;
public RankingViewHolder(View itemView)
{
super(itemView);
txt_name = itemView.findViewById(R.id.txt_name);
txt_score = itemView.findViewById(R.id.txt_score);
personPhoto = itemView.findViewById(R.id.person_photo);
txt_class = itemView.findViewById(R.id.txt_class);
ranknumber = itemView.findViewById(R.id.ranknumber);
itemView.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View view) {
itemClickListener.onClick(view , getAdapterPosition(),false);
}
}
The adapter:
adapter = new FirebaseRecyclerAdapter<Ranking, RankingViewHolder>(
Ranking.class,
R.layout.layout_ranking,
RankingViewHolder.class,
rankingTbl.orderByChild("score").limitToFirst(100)
)
This line of code int realRank = totalRanking - viewHolder.getAdapterPosition();gives a number (1,2,3,4,5,6 etc.) Why i cannot use this number to check equality?
Notice
Keeping this code for NOT working solution, just for future reference:
if(position == 0){
viewHolder.itemView.setBackgroundColor(Color.GREEN);
}
else if(position == 1){
viewHolder.itemView.setBackgroundColor(Color.YELLOW);
}
else if(position == 2){
viewHolder.itemView.setBackgroundColor(Color.BLUE);
}
else{
viewHolder.itemView.setBackgroundColor(Color.WHITE);
}
This changes the color BUT not for only 3 first items. As you scroll down, changes the color for every 3 first viewable items like before, meaning 1,2,3, 7,8,9, etc.
Update:
I dont use a custom adapter, i use FirebaseRecyclerAdapter.
Thanks to #Muhammad Haroon comment i checked that has getItemViewType. So now i m trying with it like
position =adapter.getItemViewType( 0);
if(position == 0){
viewHolder.itemView.setBackgroundColor(Color.GREEN);
}
Not working for now, but i think its the correct direction...
Update 2
With position its not possible as RecycleView recycles the views so i have the same result. The working code is
if (linearLayoutManager.findFirstVisibleItemPosition() > 0) {
viewHolder.itemView.setBackgroundResource(R.drawable.blackframe);
}
else{
viewHolder.itemView.setBackgroundResource(R.drawable.goldframe);
}
Works fine except that after scrolling loosing the change of background.
So as we want and need the perfection, any idea for keeping even after scroll?
hi try add this in your Adapater it may solve your problem.
#Override
public int getItemViewType(int position) {
return position;
}
Please give this a try
override in your custom adapter
#Override
public long getItemId(int position) {
return position;
}
and in in your adapter object:
myAdapter.setHasStableIds(true);
In populateViewHolder add these line of code
if(position == 0){
viewHolder.itemView.setBackgroundColor(Color.GREEN);
}
else if(position == 1){
viewHolder.itemView.setBackgroundColor(Color.YELLOW);
}
else if(position == 2){
viewHolder.itemView.setBackgroundColor(Color.BLUE);
}
else{
viewHolder.itemView.setBackgroundColor(Color.WHITE);
}
position is a parameter in populateViewHolder.
I have one quote application which has a "Load more" button visible only if the quote list size is 15. Now I want change the condition so that it must show the button only if the quote list size is more than 15. My current code is like below and I have tried to change it to:
if(c.getCount()<=15){
// Not Showing Load More Button
}
but it's not showing my button.
My code for that button is below:
final Button btnLoadMore=new Button(this);
btnLoadMore.setBackgroundColor(Color.parseColor("#351802"));
btnLoadMore.setTextColor(Color.parseColor("#e8d8a7"));
btnLoadMore.setTypeface(btnLoadMore.getTypeface(), Typeface.BOLD);
btnLoadMore.setText("Load More Quotes");
if(c.getCount()<15){
// Not Showing Load More Button
}
else {
list.addFooterView(btnLoadMore);}
list.setAdapter(adapter);
anifadein=AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slidedown);
list.startAnimation(anifadein);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
map = quotesList.get(position);
Intent intent = new Intent(QuotesActivity.this,
QuoteDialogActivity.class);
int itemPosition = position;
if(startingPoint>=30){
intent.putExtra("Pos", itemPosition+1);
intent.putExtra("LstCount", list.getCount()-1);
}else{
intent.putExtra("Pos", itemPosition+1);
intent.putExtra("LstCount", list.getCount());}
intent.putExtra("QuoteId", map.get(KEY_ID));
intent.putExtra("quotesType", quType);
intent.putExtra("startFrom", getIntent().getStringExtra("startFrom"));
intent.putExtra("Quotes", quotesList);
// Log.i("COUNT",""+(itemPosition+1)+"-"+list.getCount());
intent.putExtra("Fav", map.get(KEY_FAVORITE));
startActivity(intent);
if (mInterstitial.isLoaded()) {
mInterstitial.show();
}
}
});
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(btnLoadMore.getVisibility()==View.VISIBLE){
Cursor newC = null;
if (quType != 0) {
switch (quType) {
case 1:
newC = db.getQuotes(""+startingPoint);
break;
case 2:
newC = db.getFavoriteQuotes(""+startingPoint);
//page.setVisibility(View.GONE);
break;
case 3:
newC = db.getAuthorQuotes(getIntent().getStringExtra("AuthorId"),""+startingPoint);
// page.setVisibility(View.GONE);
break;
}
}
// Starting a new async task
if(newC.getCount()<15){
btnLoadMore.setVisibility(View.INVISIBLE);
}
startingPoint+=15;
do{
map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, newC.getString(newC.getColumnIndex(KEY_ID)));
map.put(KEY_TEXT, newC.getString(newC.getColumnIndex(KEY_TEXT)));
map.put(KEY_AUTHOR, newC.getString(newC.getColumnIndex(KEY_AUTHOR)));
map.put(KEY_PICTURE, newC.getString(newC.getColumnIndex(KEY_PICTURE)));
map.put(KEY_PICTURE_SDCARD, String.valueOf(newC.getInt(newC
.getColumnIndex(KEY_PICTURE_SDCARD))));
map.put(KEY_WEB_ID,
String.valueOf(newC.getInt(newC.getColumnIndex(KEY_WEB_ID))));
//Log.i("web_id",String.valueOf(newC.getInt(newC.getColumnIndex(KEY_ID))));
map.put(KEY_FAVORITE, newC.getString(newC.getColumnIndex(KEY_FAVORITE)));
// adding HashList to ArrayList
quotesList.add(map);
if (mInterstitial.isLoaded()) {
mInterstitial.show();
}
} while (newC.moveToNext());
adapter.notifyDataSetChanged(); }}
});
}
}
I not sure from where Object "c" is coming but i m assuming it list object and getCount is return the current count of list. So, If you want to show "Show more" button when the size of list is greater than or equals to 15 then use this condition.
if(c.getCount() >= 15){
// Will show Load More Button
}
Put the Button in a layout XML File. Inflate it, then:
if (c.getCount() > 15) {
btnLoadMore.setVisibility(View.INVISIBLE);
}
If you want the Button to be invisible.
I have a EditText box in which i want to control the cursor and modify the text programmatically
I have 12 button keypad made using 12 buttons in a GridView. With each button press I have a specific text which is to be inserted in EditText box at cursor position. For this i need cursor position so that i can insert the my custom text in the EditText view
I have two buttons for moving cursor position left/right by one character. Alternatively the cursor can also be set by touching EditText view (as EditText is supposed to behave)
Also i want the current position of cursor in EditText whenever Cursor position changes (I think i have to implement some kind of interface but i dont know how)
What i have tried so far
I am storing the key presses in an ArrayList<String>
I am setting the edittext.setText(String) everytime a key is pressed
can get the editable text through getText() but setText() only accepts strings.
Hence i am confused. What should i do to fulfill all my requirements.
PS: I am a Android beginner, and am making my 2nd app (which is a scientific calculator if it helps)
also if anyone volunteers to review my code, I'll be deeply obliged to him
I dont know why you need the cursor position of the textview but take a look at this question here : Get Cursor Position in Android in Edit Text?
Actually you can edit the text in the textview on code by getting the input or if you want you can implement the TextWatcher interface to know what every input the user type in your textview like this one:
private class CheckText implements TextWatcher {
#Override
public void afterTextChanged(Editable s) {
//triggers after the user changed the input on text
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
//triggers before the user changed the input on text
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
//triggers when the user changed the input on text
}
}
To set any number in EditText use Wrapper class then set it on EditText using toString().
For set position you can use editText.setSelection(position);
It is how I did something similar
Stored id of all the button in a array as shown below.
int[] kbdButtons = { R.id.button1, R.id.button2, R.id.button3,
R.id.button4, R.id.button5, R.id.button6, R.id.button7,
R.id.button8, R.id.button9, R.id.button10, R.id.button11,
R.id.button12, R.id.button13, R.id.button14, R.id.button15}
2.Then added custom Onclicklistner to all buttons in the kbdButtons array
for (int i = 0; i < kbdButtons.length; i++) {
Button buttonNum = (Button) dialoglayout
.findViewById(kbdButtons[i]);
buttonNum.setOnClickListener(hindiKbdBtnsClick);
}
and here is the declaration of custom clicklistner
private OnClickListener hindiKbdBtnsClick = new OnClickListener() {
#Override
public void onClick(View v) {
int btnId = v.getId();
if (isShift && btnId != R.id.kbdKeyLeftShift
&& btnId != R.id.kbdKeyRightShift) {
sNotPressedView.setVisibility(View.VISIBLE);
sPressedView.setVisibility(View.GONE);
isShift = false;
}
if (btnId == R.id.kbdKeyLeftShift || btnId == R.id.kbdKeyRightShift) {
if (!isShift) {
sNotPressedView.setVisibility(View.GONE);
sPressedView.setVisibility(View.VISIBLE);
isShift = true;
} else {
sNotPressedView.setVisibility(View.VISIBLE);
sPressedView.setVisibility(View.GONE);
isShift = false;
}
} else if (btnId == R.id.kbdKeySpace || btnId == R.id.kbdKeyEnter) {
hkEditText.append(" ");
} else if (btnId == R.id.kbdKeyBackSpace) {
String txt_curr_val = hkEditText.getText().toString();
if (txt_curr_val.length() != 0)
txt_curr_val = txt_curr_val.substring(0,
txt_curr_val.length() - 1);
hkEditText.setText(txt_curr_val);
hkEditText.setSelection(txt_curr_val.length());
}else if (btnId == R.id.kbdKeyHide) {
mDialog.hide();
}else {
Button b = (Button) v;
String btnText = b.getText().toString();
hkEditText.append(btnText);
}
}
};
Explanation - hkEditText is my editText view i.e.
EditText hkEditText = (EditText)FindViewById(R.id.myEdittextId);
-see I just appended the text written on the button that is pressed at that time.
-you can also see the functionality of some special buttons like space, shift and enter
Ok, so I'm trying to create an activity that works out the area of a given space.
I want the user to be able to enter the dimension in either "ft" of "m". The answer is required to be given in meters at the end.
Right, now to the problem.
The below code works, the problem is that the program assumes that both num1 and num2 are both equal to what ever is selected in the last spinner used. So if you input 100 ft for num1 then 10m for num2 it gives the answer of 1000m, because you select the m unit last. It should be giving the answer of 92.9...
This has been a headache for the last few days...
Can anyone help me!?!
Thanks in advance
Will
private OnClickListener myClickListener = new OnClickListener()
{
public void onClick(View v) {
try{
a=Double.parseDouble(num1.getText().toString());
b=Double.parseDouble(num2.getText().toString());}
catch(Exception e)
{
if(num1.getText().length()==0)
{
num1.setError("please input width");
}
if(num2.getText().length()==0)
{
num2.setError("please input length");
}
}
if (opselected=="ft" && opselected1=="ft")
{c=((a * 0.0929) * (b * 0.0929));tv1.setText(Double.toString(c));}
else if (opselected=="m" && opselected1=="m")
{c=( a * b);tv1.setText(Double.toString(c));}
else if (opselected=="m" && opselected1=="ft")
{c= (a * (b * 0.0929));tv1.setText(Double.toString(c));}
else if (opselected=="ft" && opselected1=="m")
{c= ((a * 0.0929) * b);tv1.setText(Double.toString(c));}
else {tv1.setText("select units");}
//tv1 = (TextView)findViewById(R.id.TextView01);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.car);
tv1 = (TextView)findViewById(R.id.TextView01);
button01 = (Button)findViewById(R.id.Button01);
button01.setText("Display Air Volume");
button01.setOnClickListener(myClickListener);
num1 = (EditText)findViewById(R.id.EditText01);
num2 = (EditText)findViewById(R.id.EditText02);
spinOps = (Spinner)findViewById(R.id.Spinner01);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, ops);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinOps.setAdapter(adapter);
spinOps.setOnItemSelectedListener(this);
spinOps1 = (Spinner)findViewById(R.id.Spinner02);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, ops1);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinOps1.setAdapter(adapter);
spinOps1.setOnItemSelectedListener(this);
}
public void onItemSelected (AdapterView<?> p,View v,int position,long id) {
opselected=ops[position];
opselected1=ops1[position];
tv1.setText("");
}
public void onNothingSelected(AdapterView<?> p) {
tv1.setText("");
}
Give each spinner its OWN listener. For example, where you have
spinOps.setOnItemSelectedListener(this);
Replace that with something more like this:
spinOps.setOnItemSelectedListener(new onItemSelectedListener() {
public void onItemSelected(AdapterView<?> p, View v, int position, long id) {
// get the value entered and the unit selected (e.g., val0, unit0)
}
});
Do the same (except using val1 and unit1, and it would be spinOps1....) and if the
units are different, pick one and convert the other to match. In other words, if
the user selects 39 inches for the first, and 2 meters for the second, and you want
it in meters, 39 inches = 1 m, so the result would be 3 meters.
See http://developer.android.com/reference/android/widget/AdapterView.OnItemSelectedListener.html for more information.
(Just search for onItemSelectedListener and take the first result....)
Later,
--jim
PS: yes, I know, I used inches instead of feet ... keeping it simple :-)
in onItemSelected(), you can use v.getId() to see if it was called for R.id.Spinner01 or R.id.Spinner02, and update either opselected OR opselected1, not both. for example:
public void onItemSelected (AdapterView<?> p,View v,int position,long id) {
if (v.getId() == R.id.Spinner01)
opselected=ops[position];
else if (v.getId() == R.id.Spinner02)
opselected1=ops1[position];
tv1.setText("");
}