Below is My Main activity with ColorChange method.I want to call this Colorchange method in ImageColor Class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void ColorChange() { // <----- Want to call this method in below class
ImageView blue = (ImageView) findViewById(R.id.imageView);
blue.setColorFilter(0xff000000);
}
}
And this is my class where i want to call the ColorChange method of Mainactivity.
public class ImageColor {
public void Imager() {
// Want to call my ColorChange method here
MainActivity obj = new MainActivity();
obj.ColorChange(); //<-------- Using mainactiviy object crashes my app.
}
}
I have already tried using Mainactivity as object it crashes my app.I also cannot declare my ColorChange method static because it uses findViewbyid.Please let me know if there is any way to call Color change method in this Image Color Class.
Try this way. It will help you.
public class ImageColor {
public void Imager(Activity activity) {
// Want to call my ColorChange method here
if(activity instance of MainActivity)
((MainActivity)activity).ColorChange(); //<-------- Using mainactiviy object crashes my app.
}
}
use interface to communicate with activity from non activity class. create colorChange() in interface and get the instance of interface in non activity class and call that method
class MainActivity {
interface mInterface = new interface() {
public void colorChange(){
}
}
}
pass mInterface to non activity class and call colorChange of interface when you want ..
You have to pass activity as a parameter in ImageColor class
Then call your ColorChange() method by refference of Activity.
Like This-
public class ImageColor {
Activity activity;
public ImageColor(Activity activity)
{
this.activity = activity;
}
public void Imager()
{
if(activity instance of MainActivity)
((MainActivity)activity).ColorChange();
}
}
Activity classes are created by Android. So the above method is not correct.
You have 2 ways to access the method in activity.
1 . using a static method
public static void ColorChange() {
ImageView blue = (ImageView) findViewById(R.id.imageView);
blue.setColorFilter(0xff000000);
}
}
Using a callback mechanism
public interface ImageLoadedcallback{
void onColorChanged(int color);
}
And update
public class ImageColor {
public void Imager(ImageLoadedcallback callback) {
callback.onColorChanged(color)
}
}
And In activity
public void ColorChange() {
new ImageLoader().Imager(new ImageLoadedcallback{
#Override
public void onImageLoaded(Color color){
ImageView blue = (ImageView) findViewById(R.id.imageView);
blue.setColorFilter(0xff000000);
});
}
To make it clear, make an Activity as a static variable can lead to Activity leak, so we must avoid doing that.
I suppose if the Activity where you create ImageColor object is MainActivity, you can pass MainActivity directly to achieve what you want.
public class ImageColor {
public void Imager(MainActivity activity) {
activity.ColorChange();
}
}
If you called it from other class(not from MainActivity), you can always passing MainActivity to that other class object to be used for ImageColor object.
PS: Check about java naming convention too, it will help you to write a better code
Related
I'm trying to create a generic/base form regardless if it is an activity or fragment. To make it simple, a Form can submit so:
class BaseFormActivity extends AppCompatActivity {
public abstract void submitForm();
#Override
public void setContentView(int layoutResID) {
ConstraintLayout activityBaseForm = (ConstraintLayout) getLayoutInflater().inflate(R.layout.activity_base_form, null);
FrameLayout frameBaseForm = activityBaseForm.findViewById(R.id.frame_base_form);
getLayoutInflater().inflate(layoutResID, frameBaseForm, true);
findViewById(R.id.btn_submit).setOnClickListener(v -> submitForm()) // for the sake of simplicity, there's a button that will trigger submitForm() method
super.setContentView(activityBaseForm);
}
}
Here, I just include some default layout for a form, and a button for submit that triggers the abstract method submitForm(). But, this is only for android activities. How can I make this also available for fragments without writing a BaseFormFragment? I don't want to repeat default behaviors from activity to the fragment and vice versa.
Consider it as a sample Presenter class which handle your button click and get all form fields and send to server
public class MyPresenter {
private MyPresenterIView iViewInstance;
public MyPresenter(MyPresenterIView iView){
this.iViewInstance=iView;
}
public void onSubmitClick(){
//write your logic here
String fieldOneText=iViewInstance.getFieldOneText();
sendToServer(fieldOneText);
}
private void sendToServer(String stringInfo){
//send info to server
}
}
MyPresenterIView Interface
public interface MyPresenterIView{
String getFieldOneText();
}
And use Presenter in your Activity or Fragment
//implement MyPresenterIView to your Activity or Fragment
public class MyActivity extent SomeActivity implements MyPresenterIView{
private MyPresenter myPresenter;
//in onCreate or onCreateView(if its a fragment) initialize myPresenter
protected void onCreate(..){
myPresenter=new MyPresenter(this);//this will enforce Activity/Fragment to implement IView
}
#Override //comes from MyPresenterIView
public String getFieldOneText(){
return ((EditText)findViewById(R.id.edttext_field_one)).getText().toString().trim();
}
}
I read the official Android documentation on creating an interface to be able to communicate between a parent activity and a fragment. So I did but my app crashes when I call one of the methods to get a value from the parent activity.
if have an interface like this in my fragment
public interface InteractWithFragmentA {
String getStringText();
}
In my calling activity I tested it out with a dummy text
#Override
public String getStringText(){ return "Some dummy text";}
I have a variable in FragmentA.java that's a reference to the host activity and casted to InteractWithFragmentA, but when I call the method using
_hostActivity.getStringText()
the app crashes. Is there something that I'm missing? I've seen some suggested methods for getting the host activity's variables by making them public and static or some other method but I'm trying not to couple the fragment to that activity. Thanks in advance.
Yo should do this:
Activity
public class YourActivity implements YourActivityInterface{
#Override public String getStringText(){ return "Some dummy text";}
}
Interface
public interface YourActivityInterface {
String getStringText();
}
Fragment
public class YourFragment extends Fragment {
YourActivityInterface mListener;
//your method...
mListener.getStringText()
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof YourActivityInterface) {
mListener = (YourActivityInterface) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement YourActivityInterface");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
Try this from fragment
((YourActivity) getActivity()).getStringText();
This is the method I want to access from the Activity class (ActivityName):
public MediaPlayer getBlipComp() {
return blipComp;
}
EDIT
In the activity class
public SingleGameActivity getSingleGameActivity() {
return this;
}
This is working fine in my SurfaceView class:
SingleGameActivity myActivity = ((SingleGameActivity)getContext()).getSingleGameActivity();
// Later in the code
myActivity.getBlipStart().start();
But when I pass the reference variable to the ball (normal)-class it doesn't work:
ball = new Ball(myActivity, box.getCenterX(), box.getCenterY(), currentLvl,
Color.GREEN);
Ball-class
public Ball(SingleGameActivity activity, int xPos, int yPos, int level,
int color) {
myActivity = activity;
THIS METHOD CAN NOT BE CALLED FROM THE BALL CLASS, WHY? SOLUTION?
myActivity.getBlipPlay().start();
Pass the ActivityName instance into the constructor of NormalClass like this:
public class NormalClass {
private ActivityName activity;
public NormalClass(ActivityName activity){
this.activity = activity;
}
public void doSomething()
{
activity.getBlipComp();
}
}
this line:
ActivityName name = new ActivityName();
actually creates a new Activity show.
thats not what you want.
You have to options to do this:
1. you pass the Activity show to the "normal class" and keep it as a field:
public class NormalClass {
private Activity myActivity;
and use it as you want.
2.do the same only in the activity class.
public class MyActivity extends Activity{
public static Activity myActivity;
and int the constructor assign "MyActivity.myActivity = this;"
and than use a static method like so to use your activity:
public static MediaPlayer getBlipComp(){
return myActivity.getBlipComp();
}
and than use this method like so:
MyActivity.getBlipComp();
Have Fun!
i trying to call a method that stays in my MainActivity class from custom onClickListener object. And there is something wrong with variable scope.
so in my MainActivity i have:
Button resetButton = (Button) findViewById(R.id.ResetButton);
View.OnClickListener myListener = new MyListener(GameBoard, width);
resetButton.setOnClickListener(myListener);
this is what my myListener class look like:
public class MyListener implements View.OnClickListener
{
private static MainActivity mainActivity;
public MyListener(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
#Override
public void onClick(View v) {
mainActivity.myMethod();
}
}
and method also in MainActivity that uses some MainActivity instance variables:
public void myMethod()
{
InstanceVariable++; // for example
}
Then when calling that myMethod on mainActivity object that i passing to myListener constructor by clicking resetButton i getting an error something about MainActivity InstanceVariable scope. I`m very beginner to android programming, so i cant fully understand where its coming from.
And this error disappears when i pass this InstanceVariable to constructor of myListener object. I think there should be an easier way to do that.
Change to:
public void myMethod() {
mainActivity.instanceVariable++; // for example
}
instancevariable is not visible in your MyListener class, you have to point that it ts in the mainActivity object.
If your instanceVariable is private, create getter function in mainActivity:
public void getInstanceVariable() {
return this.instanceVariable
}
and use it this way:
public void myMethod() {
mainActivity.setInstanceVariable(mainActivity.getInstanceVariable()+1); // for example
}
make InstanceVariable to
public static int InstanceVariable;
and use this
#Override
public void onClick(View v) {
MainActivity.InstanceVariable++;
}
don't make methods for function that has less than 8 lines
Try this :
Make your listener an inner class of your activity, then :
class MyListener implements View.OnClickListener {
public MyListener() {
}
#Override
public void onClick(View v) {
MainActivity.this.myMethod();
}
}
i cannot access my view script through my activity. what i want to do it:
Activity:
protected void callViewScriptFunction()
{
GameView.somefunction();
}
GameView:
protected void somefunction();
{
// do something
}
You have to first create an instance of GameView to access it:
GameView myView = new GameView();
myView.somefunction();
or you can make a static method in GameView
protected static void somefunction(){
//do something
}
then access it anywhere statically GameView.somefunction()