ovina peiris
ovina peiris

Reputation: 1

Pass an int value from one class to another?

I created an EditText to get the count of backspaces every time a user type something in that EditText and i take a count for the number of letters the users typed and get a percentage of backspaces for the number of keys user typed. But i m stuck finding a way to pass an int value from one class to another.

This is what i used to pass the int count in the class i am in now,

public void onClickNext(View v) {
    if (v.getId() == R.id.btNext) {
        String settingsstr = settings.getText().toString();
        String settingsstr2 = settings2.getText().toString();
        if (!settingsstr.equals(settingsstr2)) {
            //pop up message
            Toast pass = Toast.makeText(Display.this, "What you typed don't match", Toast.LENGTH_SHORT);
            pass.show();
        } else {

            Intent i = new Intent(Display.this, IntentService.class);
            i.putExtra("Count", count);
            startActivity(i);

        }
    }
}

count is the number of backspaces and this is how i get it.

      if ((event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_DEL))
   {
       Toast pass = Toast.makeText(Display.this, "You pressed BackSpace", Toast.LENGTH_SHORT);
       pass.show();
       count++;
   }

this is in the other class to get the count coming from the previous class. but when i run it, error occurs all the time.

        int count = getIntent().getIntExtra("Count", 0);
    TextView tv = (TextView) findViewById(R.id.TVCount);
    tv.setText(count);

Upvotes: 0

Views: 106

Answers (4)

ImDeveloping
ImDeveloping

Reputation: 101

tv.setText(Integer.toString(count));

Upvotes: 1

Bob Joe
Bob Joe

Reputation: 55

It seems like you need to add a get method to your class to pass the count variable to other classes.

See:

Proper way of getting variable from another class

For Example:

public class ButtonEvent {
int count = 0;
// Button Click Implementation
public int getCount(){
    return this.count;
  }

}

class OtherClass{
   // Do something
   public ButtonEvent buton = new ButtonEvent();
   int var = buton.getCount();
   //Do Some more
}

Upvotes: 1

Ramesh Bhupathi
Ramesh Bhupathi

Reputation: 418

Just declare the count as static variable,then u can easily acess in other classes.

public static int count=0;  //declaration

access count : classname.count

tv.setText(""+Display.count);

Upvotes: 1

Roberto Aureli
Roberto Aureli

Reputation: 1438

Have you tried this?

tv.setText(""+count);

Upvotes: 2

Related Questions