0

When the new message is received, message should be passed to the internet for my further business logic.

To receive the new messages I used onReceive of broadcastreceiver and to process the internet business logics in background I used AsyncTask.

I am getting the null pointer exception in onPostExecute method of AyncTask, I read many stackoverflow and other website solutions and created the interface and initialized it in the AsyncTask extended class constructor. But getting only nullpointer.

My Full code:

MainActivity:

public class SmsActivity extends Activity implements     ParseURL.OnAsyncRequestComplete {
private static SmsActivity inst;
public static final String SMS_BUNDLE = "pdus";
public static SmsActivity instance() {
    return inst;
}

@Override
public void onStart() {
    super.onStart();
    inst = this;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sms);
}

@Override
public void processResp(String output){
    String outpu1 = output+" in main";
}

}

BroadCastReceiver:

public class SmsBroadcastReceiver extends BroadcastReceiver{
public static final String SMS_BUNDLE = "pdus";
public void onReceive(Context context, Intent intent) {
    Bundle intentExtras = intent.getExtras();
    if (intentExtras != null) {
        Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
        String smsMessageStr = "";

        boolean rechargeResult = false;
        for (int i = 0; i < sms.length; ++i) {
            SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);
            String smsBody = smsMessage.getMessageBody().toString();
            String address = smsMessage.getOriginatingAddress();
            smsMessageStr += "SMS From: " + address + "\n";
                if (smsBody != null) {
                    String[] splitValues = smsBody.split(" ");
                    if (splitValues != null && splitValues.length > 0) {
                        String siteURL = "SITE_URL";
                        try {
                            ParseURL.OnAsyncRequestComplete procesInterf = null;
                            ParseURL urlParse = new ParseURL(procesInterf);
                            Toast.makeText(context, siteURL, Toast.LENGTH_LONG).show();
                            new ParseURL(procesInterf).execute(new String[]{siteURL});
                        } catch (Exception e) {
                            Toast.makeText(context, "123 "+e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    } else {
                        Toast.makeText(context, "split values is null", Toast.LENGTH_LONG).show();
                    }
                else {
                    Toast.makeText(context, "smsbody is null", Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}

}

ParseURL:

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


ProgressDialog progressDialog;

OnAsyncRequestComplete caller;
//Context context;


public ParseURL(OnAsyncRequestComplete a) {
    caller = a;
   // context = a;
}

public interface OnAsyncRequestComplete {
    public void processResp(String response);
}


@Override
protected void onPreExecute()
{
    progressDialog.setMessage("WAIT...");
    progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    progressDialog.setCancelable(false);
    progressDialog.show();
}



@Override
protected String doInBackground(String... strings) {
    String responseStatus = "";
    try {
        if(strings!=null) {
            if (null != strings[0]) {
                Document doc = Jsoup.connect(strings[0]).timeout(0).get();
                if (doc != null) {
                    String result = doc.select("body").text();

                    if (null != result) {

                        if (result.toLowerCase().contains("FAILED".toLowerCase())) {
                            responseStatus = result;
                        } else if (result.toLowerCase().contains("SUCCESS".toLowerCase())) {
                            responseStatus = "SUCCESS";
                        } else {
                            responseStatus = "FAILED";
                        }
                    } else {
                        responseStatus = "google";
                    }
                } else {
                    responseStatus = "facebook";
                }
            } else {
                responseStatus = "youtube";
            }
        }else{
            responseStatus = "ebay";
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }
    return responseStatus;
}


@Override
protected void onPostExecute(String s) {
    caller.processResp(s);
}

}

I tried many solutions which is shared in the stackoverflow and other sites. But I could not solve it. Please do not mark this as duplicate.

Thanks in advance.

Naveen
  • 117
  • 2
  • 11

2 Answers2

1

Ohh maaan...

ParseURL.OnAsyncRequestComplete procesInterf = null;
ParseURL urlParse = new ParseURL(procesInterf);

   public ParseURL(OnAsyncRequestComplete a) {
        caller = a;
    }

@Override
protected void onPostExecute(String s) {
    caller.processResp(s);
}

Are You see mistake?

You pass null to the ParseUrl constructor, so on PosteExecute() tries to call a method of a null callback.

I suspect that you would like to do that

ParseURL.OnAsyncRequestComplete procesInterf = SmsActivity.this;

But it will work, if your SmsBroadcastReceiver class is a inner class of SmsActivity.

Sirelon
  • 6,446
  • 5
  • 26
  • 30
  • Chris Stratton, I am write above for problem, and illustrated it by code. Or do you mean my bad English? – Sirelon Apr 23 '15 at 20:25
  • 1
    Thanks that is a little better, though something like "You pass null to the ParseUrl constructor, so onPostExecute() tries to call a method of a null callback" would be clearer. – Chris Stratton Apr 23 '15 at 20:30
  • sirelon, when I try ParseURL.OnAsyncRequestComplete procesInterf = SmsActivity.this; in SmsBroadCastRecevier.java i am getting the compilation error like "is not an enclosing class". And you mentioned like it will work if it would have been a inner class of smsactivity. Can you share me the snippet to try. – Naveen Apr 23 '15 at 20:44
  • You need to initialize procesInterf. Not null! Easy way be a this: `ParseURL.OnAsyncRequestComplete procesInterf = new OnAsyncRequestComplete(){ @Override public void processResp(String output){ String outpu1 = output+" in main"; }` – Sirelon Apr 23 '15 at 20:51
  • That to use inner broadcastreciever you need to register broadcast in your activity class. – Sirelon Apr 23 '15 at 20:54
0

You never initialize caller. Basically you set it to null, then you pass it to your AsyncTask, then you try to use it.

You already use the singleton pattern in your Activity, so you were probably after

ParseURL.OnAsyncRequestComplete procesInterf = SmsActivity.instance();

async
  • 1,537
  • 11
  • 28
  • please share me the sample code that what need to be changed and tried. – Naveen Apr 23 '15 at 20:37
  • @NaveenkumarGunasekaran Where do you register that `BroadcastReceiver` ? – async Apr 23 '15 at 20:45
  • I implemented the interface to process the onPostExecute result further – Naveen Apr 23 '15 at 20:47
  • I understand your intention, however your `BroadcastReceiver` has no knowledge of your `Activity` (which is where your implementation of the interface is. I'll edit my answer. – async Apr 23 '15 at 20:51
  • @NaveenkumarGunasekaran I think I understood your intention now. Give that a try. – async Apr 23 '15 at 21:00
  • Thrasher: I changed the code like you mentioned but still i am getting this toast, `Toast.makeText(context, "123 "+e.getMessage(), Toast.LENGTH_LONG).show();` printing 123null – Naveen Apr 23 '15 at 21:10
  • What's the problem now? – async Apr 23 '15 at 21:13
  • Ah, of course, what was I thinking. You'll probably have to register the `BroadcastReceiver` manually in your `Activity`. Create a field in your activity that holds your `BroadcastReceiver`, instantiate it in `onCreate()` and `register` and `unregister` it. See this answer for how to register / unregister: http://stackoverflow.com/a/18842810/1991295 – async Apr 23 '15 at 21:17
  • @NaveenkumarGunasekaran Add a comment if you still need help with the new approach. :P – async Apr 23 '15 at 21:35
  • @Thrasher: i updated like this,but no luck: `@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sms); filter1 = new IntentFilter("android.provider.Telephony.SMS_RECEIVED"); registerReceiver(myReceiver, filter1); } private final BroadcastReceiver myReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { } }; @Override public void onDestroy() { unregisterReceiver(myReceiver); }` – Naveen Apr 23 '15 at 21:40
  • @NaveenkumarGunasekaran Are you still getting the same error or is it something else now? – async Apr 23 '15 at 21:43
  • @Thrasher: Still getting the same null pointer exception. I do not know whats the mistake I am doing really. – Naveen Apr 24 '15 at 03:42