I Want to put all my methods in seperate classes to clean my code up when creating my Android App but i can seem to get it right.
In my MainActivity class i call the method from the importet class noteFunctionality onLongpress and OnDoubleTap.
@Override
public void onLongPress(@NonNull MotionEvent e) {
noteFunc.enterNote("2");
super.onLongPress(e);
}
@Override
public boolean onDoubleTap(@NonNull MotionEvent e) {
noteFunc.enterNote(2);
return super.onDoubleTap(e);
}
Then in my NoteFunctionality class i try start the a new activity class with the given int for the specifik activity, "I have more then one activity".
public void enterNote(int i) {
Class mainActivity = Class.forName("MainActivity" i);
Intent secondActivityIntent = new Intent(this, mainActivity.class);
startActivity(secondActivityIntent);
}
What am I doing wrong?.
CodePudding user response:
public void enterNote(Activity activity,Context context) {
//Class mainActivity = Class.forName("MainActivity" i);
Intent secondActivityIntent = new Intent(context, activity.getClass());
startActivity(secondActivityIntent);
}
and when you call it
noteFunc.enterNote(MainActivity,yourActivity.this);
CodePudding user response:
If you would like to trigger another Activity, it must be done through Context
.
Therefore, you need to pass Context
to your NoteFunctionality
function to achieve your task.
MainActivity:
public class MainActivity extends Activity { // or extending any other form of Activity
NoteFunctionality noteFunc; // I assume you have properly assign it somewhere
@Override
public void onLongPress(@NonNull MotionEvent e) {
// You will have to pass also Context to enterNote function
noteFunc.enterNote(MainActivity.this, "2"); // You should pass an Integer instead of String here
super.onLongPress(e);
}
@Override
public boolean onDoubleTap(@NonNull MotionEvent e) {
noteFunc.enterNote(MainActivity.this, 2);
return super.onDoubleTap(e);
}
}
NoteFunctionality:
public class NoteFunctionality {
// You need to have Context here
public void enterNote(Context context, int i) {
Intent secondActivityIntent = new Intent(context, SecondActivity.class); // Replace your target Activity name with SecondActivity
context.startActivity(secondActivityIntent);
}
}