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("");
}
Related
I have made a sample chat layout which just adds the EditText input to a RecyclerView, but as you see in this picture after the fifth item it doesn't work the way it shoud (the numbers are the EditText outputs)
Fragment class =>
Boolean me = true ;
Boolean seen = false ;
#Override
public void onClick(View view) {
if (view.getId() == R.id.send_button) {
me = !me ;
seen = !seen ;
sendMessage();
}
}
private void sendMessage(){
String editTextString = editText.getText().toString() ;
Calendar calendar = Calendar.getInstance() ;
String time = calendar.get(Calendar.HOUR) + ":" + calendar.get(Calendar.MINUTE) ;
first_message.setVisibility(View.GONE);
if (editTextString.equals("")){
return;
}
E08Object object = new E08Object();
object.setMessage(editText.getText().toString());
object.setDate(time);
object.setMe(me);
object.setSeen(seen);
list.add(object) ;
adapter.notifyDataSetChanged();
fragment_recyclerView.smoothScrollToPosition(list.size());
editText.setText("");
}
Adapter class =>
#Override
public void onBindViewHolder(#NonNull VH holder, int position) {
holder.textView.setText(list.get(position).getMessage());
holder.timeTextVIew.setText(list.get(position).getDate());
if (!list.get(position).getMe()) {
holder.seenImage.setVisibility(View.GONE);
holder.fragmentParent.setBackground(ContextCompat.getDrawable(Application.getContext() , R.drawable.person_message_rounded));
}
}
Please check. You must reset value in else block inside bindViewHolder as the views are recycled.
if (!list.get(position).getMe()) {
holder.seenImage.setVisibility(View.GONE);
holder.fragmentParent.setBackground(ContextCompat.getDrawable(Application.getContext() , R.drawable.person_message_rounded));
} else {
holder.seenImage.setVisibility(View.VISIBLE);
holder.fragmentParent.setBackground(ContextCompat.getDrawable(Application.getContext() , R.drawable.THE_DEFAULT_DRAWABLE));
}
This should help if this issue is due to recycling. Let me know if this helps. Also, better to attach the item layout and the recycler layout.
My question is simple. What method can I use to tell my program that a button is pressed? I'm trying some codelines but its not really working (I tryed with isPressed). in my logs I can read the line --> TAMAÑO DEL CONTADOR: < the numbers until it reaches max.> before I can I even place a value, so I understand the loop doesnt wait for my inputs.
Here is my code:
public class navegador extends AppCompatActivity {
public String Sdat;
public EditText ET2;
int tam;
ArrayList<String> Medidas;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navegador);
ET2 = findViewById(R.id.ET1);
Button bot = findViewById(R.id.bot);
tam = getIntent().getIntExtra("numero",0);
Medidas = new ArrayList<>();
int contador = 0;
System.out.println("TAMAÑO DEL ARRAY: "+ tam);
while ( contador <= tam){
System.out.println("TAMAÑO DEL CONTADOR: " + contador);
bot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View bot) {
if(bot.isPressed()){
MeterMedida();
}
}
});
contador++;
if(contador == tam){
Toast.makeText(this, "Distancia máxima alcanzada. Toca Crear tabla.", Toast.LENGTH_SHORT).show();
}
}
}
public void MeterMedida(){
Sdat = ET2.getText().toString();
Medidas.add(Sdat);
ET2.setText("");
}
public void LanzarLista (View view){
Intent A = new Intent(this, Lista.class);
A.putStringArrayListExtra("Lista", Medidas);
startActivity(A);
}
}
Thanks a lot, ask me for more information if you think you need it.
EDIT
As usual, less is more, I removed the while, and contador variable, now it works like I wanted and its pretty much simple. Thank you so much.
You said that you wanted to tell your app when a button is pressed, do something. There's no need to use isPressed() method. Just do it like this.
bot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View bot) {
//When you press this button (bot), codes here will be executed.
MeterMedida();
}
});
You don't need a while loop:
//a list to keep all the entered floats
private List<Float> floats = new ArrayList<Float>();
//each time you click the listener is invoked
bot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View bot) {
//every time the button is clicked, fill the current typed float
floats.add(Float.parseFloat(ET2.getText().toString()));
ET2.setText("");
}
});
Well, I’m not gonna give complete answer. Just a few hints for yourself to figure out.
Declare int contador = 0; in class level
Remove while ( contador <= tam)
Remove if(bot.isPressed())
Remove contador++; in your onCreate
Inside MeterMedida() check for if(contador <= tam). If true, add to ArrayList and increment contador. Else show error Toast.
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.
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?
I've checked other questions here on setTag and getTag, but I don't get it.
I'm setting tag here
buttonA.setOnClickListener(new View.OnClickListener() {
public int GetRandomNumber(int max) {
int min;
min = 1;
int num = min + (int) (Math.random() * ((max - min) + 1));
return num;
}
int RandomIndex;
public void onClick(View view) {
int countMax = 40;
RandomIndex = GetRandomNumber(countMax);
view.setTag(RandomIndex);
}
});
And getting tag here
buttonB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
int Index = (Integer)(view.getTag());
tv1.setText(Index);
}
});
I'm getting NullPointerException error, therefore I haven't used the setTag correctly..
This is happening in 1 Activity.
You setTag() on a single View object, to store some information associated with the View
View.setTag(Object tag)
In your example you are setting the Tag of ButtonA and then calling getTag on ButtonB. Of course it is empty, you never set a tag on ButtonB.
The View in the onClick is the View you are clicking on. In this case you are setting on one view and getting from a different view. It will always be null.
Edit: I think for your purposes just use a class variable to store and retrieve what you want. getTag() isn't some magic form of communication between views :)
You are trying to call setText with an Integer-Value. By doing this android thinks you want to deliver a ressource-ID (e.g. R.string.mytext which are integer values in your R-Class). Android/Java cannot decide wether you want to display a number or a ressource-String. Just change it to tv1.setText("" + Index); and your integer will be delivered as String to setText()-Method.
Ken Wolf's answer tells you why it isn't working. To fix it you can simply make that variable a member variable so it can be accessed anywhere in your Activity
public class YourClass extends Activity
{
int RandomIndex; // initialize variable here
public void onCreate(...)
{
...
}
buttonA.setOnClickListener(new View.OnClickListener() {
public int GetRandomNumber(int max) {
int min;
min = 1;
int num = min + (int) (Math.random() * ((max - min) + 1));
return num;
}
public void onClick(View view) {
int countMax = 40;
RandomIndex = GetRandomNumber(countMax); // set value here
}
});
and use the value here
buttonB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
tv1.setText(String.valueOf(RandomIndex)); // use value here
}
});
Also, to conform with Java naming conventions, you should use mixed-case for your variables so RandomIndex would be randomIndex. That's just a suggestion that may make life easier if you work with other developers or when people are looking at your code to help you.