0

hi i have created a global actions class and created functions inside this class which i'm trying to access inside another activity the problem i'm having is that in eclipse I'm getting coding errors around the functions that access system feature such as getSystemService() and getApplicationContext() does anyone know why or how to let a global class accept system features?

heres what i have so far heres my GloblActions.java

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

public class GlobalActions{
        Context mContext;

        // constructor
        public GlobalActions(Context context){
            this.mContext = context;
        }


        public final static boolean isOnline (Context someContext){ {

            Log.v("globals", "isonline");

    ConnectivityManager cm = (ConnectivityManager) someContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();

        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
        }

}



        public final static void checkInternet(Context someContext){

                    isOnline(someContext);
                    if(isOnline(someContext) == false){
                       Log.v("globals", "isOnline = false");
                       Intent register = new Intent(someContext.getApplicationContext(), LoginForm.class);
                       someContext.startActivity(register);
                    }
                }



        }   

heres where i'm using the function in an activity. my goal is is to check internet connection on every activity by just calling the global function and if no connection is found go to an activity that says no internet connection.

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import android.os.Handler;
import com.myApp.myApp.GlobalActions;

public class IntroLoader extends Activity {

    public Handler handler;
    public TextView loadText = null;
    public Animation AniFadein = null;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.lo_introloader);
        findViewById(R.id.progressBar1).setVisibility(View.GONE);
        findViewById(R.id.loadTextView).setVisibility(View.GONE);
         GlobalActions.isOnline(null);
         GlobalActions.checkInternet(null);

        handler = new Handler();
        final Runnable fadeIn = new Runnable()
        {
            public void run() 
            {
               animations();
               findViewById(R.id.progressBar1).setVisibility(View.VISIBLE);
               findViewById(R.id.loadTextView).setVisibility(View.VISIBLE);
                         }
        };
        handler.postDelayed(fadeIn, 3000);

        final Runnable aSyncTask= new Runnable()
        {
            public void run() 
            {

               PostTask posttask;
               posttask = new PostTask();
               posttask.execute();

            }
        };
        handler.postDelayed(aSyncTask, 4000);

    }

    public void animations(){

        loadText = (TextView)findViewById(R.id.loadTextView);
        AniFadein = AnimationUtils.loadAnimation(this, R.anim.fadein);  
        loadText.startAnimation(AniFadein); 

    }


  public class PostTask extends AsyncTask<Void, String, Boolean> {

        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected Boolean doInBackground(Void... params) {
            boolean result = false;
            publishProgress("progress");
            return result;
        }

        protected void onProgressUpdate(String... progress) {
            StringBuilder str = new StringBuilder();
                for (int i = 1; i < progress.length; i++) {
                    str.append(progress[i] + " ");

                }
        }

            @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            checkLoginData();
          }
    }

  public void checkLoginData(){

      Intent register = new Intent(getApplicationContext(), LoginForm.class);
      startActivity(register);


  }         



}
Luke Batley
  • 2,384
  • 10
  • 44
  • 76
  • You may want to look at http://developer.android.com/reference/android/app/Application.html – MrZander Jan 23 '13 at 21:01
  • @MrZander I wouln't recommend extending Application and neither do the docs: *"There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way."* – A--C Jan 23 '13 at 21:17

1 Answers1

2

Do

 ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);

Contexts can use the method getSystemService() but your class isn't a Context, you need to use your mContext variable.

This means that you can also replace getApplicationContext() with mContext. And if you really need getApplicationContext() (unlikely - normal Contexts should work fine), use

mContext.getApplicationContext()

Also, you declare your isOnline() method as static, but then you need to use a Context for checking and making the toast. Either don't make it static or change it so it accepts in a Context, eg

public final static boolean isOnline (Context someContext){

And replace calls there that need a Context with someContext. Static methods don't need an instance of the class, and so, you can't use mContext. Once you fix the getApplicationContext() issue you have now, the compiler should throw an error about accessing a non static field in a static way. Same with your checkInternet(). I suggest you revaluate your logic, there are multiple problems with your class - I suggest making everything a static method that accepts in a Context which will be given by the calling Activity.

Lastly be careful about showing Toasts and other UI Elements in a global non-ui class. Toasts should be fine since they run on top of windows, but a Dialog will need a window, and if mContext is not an instance of Activity, that will fail (Activities have a window, other Contexts (like getApplicationContext()), do not.

A--C
  • 36,351
  • 10
  • 106
  • 92
  • hi this is great thank you nice to have an answer not only given but explained. one thing i'm having an issue with is is asking me to change modifier of mContext to static which is causing it to break still do you know why this is? – Luke Batley Jan 23 '13 at 21:11
  • @LukeBatley you can't access non-static fields in a static method. I really suggest you make this whole class contain only static methods and have each Activity pass itself off as a Context for each method call. Having this class be instantiated (via `new`) is a waste - not to mention is causes more problems. – A--C Jan 23 '13 at 21:15
  • thanks for your help i have edited my code to what i think you were suggesting is what i have done correct? – Luke Batley Jan 23 '13 at 21:25
  • @LukeBatley seems correct to me. Note that now you don't need the constructor nor do you need `Context mContext;`. – A--C Jan 23 '13 at 21:28
  • I'm getting a null pointer exception error at ConnectivityManager cm = (ConnectivityManager) someContext.getSystemService(Context.CONNECTIVITY_SERVICE); – Luke Batley Jan 23 '13 at 21:35
  • You're passing off null in the Activity: `GlobalActions.isOnline(null); GlobalActions.checkInternet(null);` replace null in this case with `this`. – A--C Jan 23 '13 at 21:37
  • 1
    thank you so much its been a pleasure to talk to someone so willing to help thanks very much – Luke Batley Jan 23 '13 at 21:39
  • hi sorry to bother you could take a look at my latest question as you were so helpful last time http://stackoverflow.com/questions/14873137/passing-functions-into-a-global-asynctask-android – Luke Batley Feb 14 '13 at 11:16