-3

I already searched on this but couldnt find the answer as I dont know in which side I am doing wrong. Whenever I class this method I got the error from where I am calling.

I am calling from this method in checkpass.java class

 private void checking() {
    okbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            TestClass testClass = new TestClass();
            testClass.testing();

        }
    });
}

I am calling this method which is located in another class

public void testing(){
    Toast.makeText(TestClass.this, "Testing class", Toast.LENGTH_SHORT).show();
}

I am getting this error:

at android.widget.Toast.makeText(Toast.java:287)
at com.futureappspk.WeTextFree.TestClass.testing(TestClass.java:18)
at com.futureappspk.WeTextFree.CheckPass$1.onClick(CheckPass.java:43)
at android.view.View.performClick(View.java:4746)
robinHood013
  • 209
  • 1
  • 2
  • 15

2 Answers2

6

testClass is not Activity so you failed here TestClass.this.

Better to pass context to testing(Context mContext){ and used it

public void testing(Context mContext){
Toast.makeText(mContext, "Testing class", Toast.LENGTH_SHORT).show();
}

and call from anywhere

testClass.testing(yourActivity.this);
M D
  • 47,665
  • 9
  • 93
  • 114
0

Since you need the Context to be able to Toast, you would want to pass your Context to this other class, either when you are calling testing, or when you are initializing the Testing() object. Your context, if in an activity can be obtained by calling getApplicationContext(). Simply passing [ACTIVITY_NAME].this would also work.

** passing to function ** [I find this preferable]

otherActivityObject.testing(thisActivity.this);

** at init **

OtherActivity otherActivityObject = new OtherActivity(thisActivity.this); otherActivityObject.testing();

Debosmit Ray
  • 5,228
  • 2
  • 27
  • 43