Search code examples
javaandroidbroadcastreceiver

Starting an AsyncTask when device connected to internet


I know that there are plenty of questions about that problem -and i've read all of them- but my real problem is with the context concept. What i'm trying to do is sniff the connectivity change with broadcast receiver, and if device connect the internet, start the AsyncTask. Acoording to logs, i can see the "Connection detected and task is starting" log when i turn off internet connection and it doesn't throw and exception and works fine. But when i turn on the internet, i can see the log again and getting error right after. And i ended up with this java null pointer exception problem every time.

NetworkChangeReceiver.java

package com.example.bitirmeson;

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

public class NetworkChangeReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, final Intent intent) {

     System.out.println("Broadcast has received.");

     ConnectivityManager cm = ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
     NetworkInfo netInfo = cm.getActiveNetworkInfo();
     if (netInfo != null && netInfo.isConnectedOrConnecting()&& cm.getActiveNetworkInfo().isAvailable()&& cm.getActiveNetworkInfo().isConnected()) 
     {
        System.out.println("Connection detected and task is starting.");
        FtpAsync task1 = new FtpAsync(null);
        task1.execute();
     }
 }
}

FtpAsync.java

package com.example.bitirmeson;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;

import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPCmd;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;

public class FtpAsync extends AsyncTask <Void, Void, String>{

private ProgressDialog mDialog;
private Activity activity;

public FtpAsync(Activity activity) {
    this.activity = activity;
    this.mDialog = new ProgressDialog(activity);
}

@Override
protected void onPreExecute() {
   super.onPreExecute();
   mDialog.setMessage("Veriler alınıyor, lütfen bekleyiniz.");
   mDialog.show();
   mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
   mDialog.setCancelable(true);
}

@Override
protected String doInBackground(Void... params) {
    // TODO Auto-generated method stub

        String theString = "";

        FTPClient ftpClient = new FTPClient();

    try {
            ftpClient.connect("f11-preview.125mb.com", 21);
            System.out.println(ftpClient.getReplyString());
            ftpClient.enterLocalPassiveMode();
            System.out.println(ftpClient.getReplyString());
            ftpClient.sendCommand(FTPCmd.USER, "1678578");
            System.out.println(ftpClient.getReplyString());
            ftpClient.sendCommand(FTPCmd.PASS, "ertan1991");
            System.out.println(ftpClient.getReplyString());
            ftpClient.sendCommand(FTPCmd.CWD, "/CodeJava");
            System.out.println(ftpClient.getReplyString());
            System.out.println(ftpClient.getReplyString());
            InputStream is= (ftpClient.retrieveFileStream("deneme1.txt")); 
            System.out.println("Input Stream has opened.");
            StringWriter writer = new StringWriter();
            IOUtils.copy(is, writer, "UTF-8");
            theString = writer.toString();
            System.out.println(theString);   
        } 

    catch (IOException ex) {
            System.err.println(ex);
      }
     return theString;
}

protected void onPostExecute(String deger) {
        // TODO: check this.exception 
        // TODO: do something with the feed
        //super.onPostExecute(deger);
    if (this.mDialog.isShowing()) {
           this.mDialog.dismiss();
        }
        IkinciEkran.text1.setText(deger);
        }
}

My LogCat file :

05-23 19:05:36.585: I/System.out(20836): Broadcast has received.
05-23 19:05:36.585: I/System.out(20836): Connection is detected and task is starting.
05-23 19:05:36.585: D/AndroidRuntime(20836): Shutting down VM
05-23 19:05:36.585: W/dalvikvm(20836): threadid=1: thread exiting with uncaught exception (group=0x40faf2a0)
05-23 19:05:36.595: E/AndroidRuntime(20836): FATAL EXCEPTION: main
05-23 19:05:36.595: E/AndroidRuntime(20836): java.lang.RuntimeException: Unable to start receiver com.example.bitirmeson.NetworkChangeReceiver: java.lang.NullPointerException
05-23 19:05:36.595: E/AndroidRuntime(20836):    at android.app.ActivityThread.handleReceiver(ActivityThread.java:2269)
05-23 19:05:36.595: E/AndroidRuntime(20836):    at android.app.ActivityThread.access$1600(ActivityThread.java:134)
05-23 19:05:36.595: E/AndroidRuntime(20836):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1294)
05-23 19:05:36.595: E/AndroidRuntime(20836):    at android.os.Handler.dispatchMessage(Handler.java:99)
05-23 19:05:36.595: E/AndroidRuntime(20836):    at android.os.Looper.loop(Looper.java:137)
05-23 19:05:36.595: E/AndroidRuntime(20836):    at android.app.ActivityThread.main(ActivityThread.java:4867)
05-23 19:05:36.595: E/AndroidRuntime(20836):    at java.lang.reflect.Method.invokeNative(Native Method)
05-23 19:05:36.595: E/AndroidRuntime(20836):    at java.lang.reflect.Method.invoke(Method.java:511)
05-23 19:05:36.595: E/AndroidRuntime(20836):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
05-23 19:05:36.595: E/AndroidRuntime(20836):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
05-23 19:05:36.595: E/AndroidRuntime(20836):    at dalvik.system.NativeStart.main(Native Method)
05-23 19:05:36.595: E/AndroidRuntime(20836): Caused by: java.lang.NullPointerException
05-23 19:05:36.595: E/AndroidRuntime(20836):    at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:142)
05-23 19:05:36.595: E/AndroidRuntime(20836):    at android.app.AlertDialog.<init>(AlertDialog.java:98)
05-23 19:05:36.595: E/AndroidRuntime(20836):    at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
05-23 19:05:36.595: E/AndroidRuntime(20836):    at com.example.bitirmeson.FtpAsync.<init>(FtpAsync.java:22)
05-23 19:05:36.595: E/AndroidRuntime(20836):    at com.example.bitirmeson.NetworkChangeReceiver.onReceive(NetworkChangeReceiver.java:21)
05-23 19:05:36.595: E/AndroidRuntime(20836):    at android.app.ActivityThread.handleReceiver(ActivityThread.java:2262)

Solution

First, i've started new blank activity from my NetworkChangeReceiver class, then i started AsyncTask from there and finish the activity.


Solution

  • You can't create Dialogs from a BroadcastReceiver, only from Activities. You should launch an Activity from your BroadcastReceiver, and show the dialog from there. Don't use setContentView if you just want the dialog to show, and not an empty screen.

    Look at this answer: http://www.stackoverflow.com/a/8766864/1199931