Vishva Nath Singh
Vishva Nath Singh

Reputation: 49

AsyncTask task is not working if internet in unable

I am trying to execute an AsyncTask but it is not running if internet in disable. As soon as i turn on the internet, AsyncTask call

LocalGroupUser localGroupUser = new LocalGroupUser(this);
    localGroupUser.execute(group.getGroupID());

AsyncTask

   /**
 * Created by mindit on 3/15/2016.
 */
public class LocalGroupUser extends AsyncTask<String,Void,String> {
    Activity activity;

    public LocalGroupUser(Activity context)
    {
        this.activity = context;
    }

    @Override
    protected String doInBackground(String... params) {
        String groupId = params[0];
        GroupDB groupDB = new GroupDB(this.activity);
      GlobalData.users = groupDB.getgroupUser(groupId);
        return String.valueOf(true);
    }

    public void onPostExecute(String result)
    {
        if(GlobalData.users!=null) {
            ((main_ui) this.activity).showUsersFromLocal();
        }
    }

}

Upvotes: 0

Views: 189

Answers (3)

Gabe Sechan
Gabe Sechan

Reputation: 93613

AsyncTasks don't run on separate threads- they all run on one thread in the order they're executed (by default). So if you have

taskWithNetworkNeeded.execute();
taskWithoutNetwork.execute();

Then taskWithoutNetwork will not run until taskWithNetworkNeeded finishes. Which obviously requires the internet.

To get around this, don't use execute. Use executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) This will force the async task to get its own thread (use this on the without network one at a minimum).

Upvotes: 2

ankur jain
ankur jain

Reputation: 51

Please include the

<uses-permission android:name="android.permission.INTERNET" /> in your manifest file.

before calling the async task please check the condition for internet connectivity

Upvotes: 0

Akshat Vajpayee
Akshat Vajpayee

Reputation: 324

Pal! You can this code as I am assuming that you are getting any data over the network! if the method return true you can call the async task otherwise show a Toast.

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class ConnectionDetector {

    private Context _context;

    public ConnectionDetector(Context context){
        this._context = context;
    }

    public boolean isConnectingToInternet(){
        ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivity != null)
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null)
                  for (int i = 0; i < info.length; i++)
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }

          }
          return false;
    }
}

Upvotes: 0

Related Questions