kjmb
kjmb

Reputation: 35

Problem with a static method: "cannot be referenced from a static context"

I have this method that I have in every activity (which just works) but can I make a 1 activity like API and call this function from any activity? and would this be a good solution? Instead of having the same function in every activity?

I have this function in a clean activity and want to call this function from any activity. In these lines I get the error: cannot be referenced from a static context

final String email = SharedPrefManager.getInstance(this).getUserEmail();
final TextView bottom_bar_points = findViewById(R.id.bottom_bar_points);
...
MySingleton.getmInstance(this).addToRequestQueue(request);

I would love to see some advice, thanks in advance.

Code

    public static void getMyPoints() {
        final String email = SharedPrefManager.getInstance(this).getUserEmail();
        final TextView bottom_bar_points = findViewById(R.id.bottom_bar_points);
        String uRl = "https://mywebsite.com/getmypoints.php";
        StringRequest request = new StringRequest(Request.Method.POST, uRl, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (response.equals("Found")) {
                    bottom_bar_points.setText(response);
                    return;
                } else {
                    bottom_bar_points.setText(response);
                    return;
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                bottom_bar_points.setError(error.toString());
                return;
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> param = new HashMap<>();
                param.put("email", email);
                return param;
            }
        };
        request.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        MySingleton.getmInstance(this).addToRequestQueue(request);
    }

Upvotes: 2

Views: 1595

Answers (4)

Lenoarod
Lenoarod

Reputation: 3620

Firstly, I will explain the reason. according to the class loader mechanism. the static variable and method which is load when compile. but the instantiation object, in the current situation; it is this. it is created when the program runs. so you can not directly use it.

Secondly, there have some solutions. one you can do pass it by a method params. but you should take care of the memory leak. if your SharedPrefManager is a single object. I don't suggest to use this way. you should use the ApplicationContext. if not it is no problem.

if wan to use it you can replace the context(this) use the application context.

public static void getMyPoints(Context context)

besides it, you can also create a base activity, then others Activity extends it. the method can use in every subclass activity.

class BaseActivity {
  public void getMyPoints(){ 
    ....
  }
}

class SubActivity extend BaseActivty{

   public void doSomething(){
       getMyPoints();
   }

}




Upvotes: 0

lettomobile
lettomobile

Reputation: 316

Add these 2 parameters to the function:

Activity A {

    public static void getMyPoints(Context context, View view) {

       ...

    }

}

and change your lines in which you get the error as I do below:

final String email = SharedPrefManager.getInstance(context).getUserEmail();
final TextView bottom_bar_points = view.findViewById(R.id.bottom_bar_points);
...
MySingleton.getmInstance(context).addToRequestQueue(request);

You can call this method in this way:

Activity B {

   A.getMyPoints(getApplicationContext(), getCurrentFocus());

}

Upvotes: 0

Akram Bensalem
Akram Bensalem

Reputation: 101

Just delete this and ad a Context variable with parameters:



public static void getMyPoints(Context contex) {
.....
}

So you replace this by context. Your code will be :



public static void getMyPoints(Context context) {

final String email = SharedPrefManager.getInstance(context).getUserEmail();
final TextView bottom_bar_points = **findViewById**(R.id.bottom_bar_points);
String uRl = "https://mywebsite.com/getmypoints.php";
StringRequest request = new StringRequest(Request.Method.POST, uRl, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        if (response.equals("Found")) {
            bottom_bar_points.setText(response);
            return;
        } else {
            bottom_bar_points.setText(response);
            return;
        }
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        bottom_bar_points.setError(error.toString());
        return;
    }
}) {
    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        HashMap<String, String> param = new HashMap<>();
        param.put("email", email);
        return param;
    }
};
request.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getmInstance(context).addToRequestQueue(request);

}



in your activity call this method with:



Activity.getMyPoints(getBaseContext())



Upvotes: 1

vahab-balouchzahi
vahab-balouchzahi

Reputation: 247

you can use from interface like below:
it is better to seperate your app data logic and view best is use inteface.. do it is testable and clean

public class GetFromServer{
        private OnGetDataListener listener;
        public getData(){
          String uRl = "https://mywebsite.com/getmypoints.php";
          StringRequest request = new StringRequest(Request.Method.POST, uRl, new 
          Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                listener.onGetData(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                 listener.onGetData(error.toString());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

            }
        };
        request.setRetryPolicy(new DefaultRetryPolicy(30000, 
        DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 
         DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
     }
     public void setOnGetDataListener(OnGetDataListner listner){
       this.listener=listener;
     }
     public interface OnGetDataListner{
       void onGetData();
    }
  }

in All activity that you neeed do this:

 public Activty extends AppCompactActivty implements{

      public onCreate(){
        new GetFromServer().setOnGetDataListener(this);
      }
      public void onGetData(String response){
        //here you can use from response
      }

}

Upvotes: 0

Related Questions