I am trying to make http request every 10 sec and then update my UI text with with current time, Below is the srvice class which is throwing this error -
public class MyService extends Service {
Handler handler;
MainActivity refer;
public MyService(){
}
public MyService(Handler handle,MainActivity ref) {
super();
this.handler= handle;
this.refer = ref;
Log.i("MyService","=============Inside MyService=========");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Handler().postDelayed(new Runnable() {
public void run() {
String res = makeRequest("www.ggggggg.com","Hello World");
refer.update(res); // Update is main activity function
}
}, 10000);
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public static String makeRequest(String uri, String json) {
Log.i("MyService","===============Inside makeRequest===================");
try {
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(new StringEntity(json));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
//return new DefaultHttpClient().execute(httpPost);
// Since dummy server so response will be null so hardcoding it to current time
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss",Locale.getDefault());
return (df.format(new Date()));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Error is this ---
09-29 15:36:10.637 1797-1797/com.google.richa.testapp E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.ttni.richa.ttnitestapp, PID: 1797 java.lang.NullPointerException: Attempt to invoke virtual method 'void com.ttni.google.testapp.MainActivity.update(java.lang.String)' on a null object reference at com.google.richa.testapp.MyService$1.run(MyService.java:40) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5221) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 09-29 15:41:10.685 1797-1797/com.google.richa.testapp I/Process﹕ Sending signal. PID: 1797 SIG: 9