RxAndroid debounce google maps on camera change - java

I have an application which is using google maps and listening on camera change. My problem is that on each camera change I have to request my backend. What I want to do is just limiting the number of requests by using RxAndroid/Java to debounce.
My code looks like this:
Observable.create(new Observable.OnSubscribe<CameraPosition>() {
#Override
public void call(Subscriber<? super CameraPosition> subscriber) {
if (!subscriber.isUnsubscribed()) {
map.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition cameraPosition) {
subscriber.onNext(cameraPosition);
}
});
}
}
}).subscribeOn(AndroidSchedulers.mainThread())
.observeOn(AndroidSchedulers.mainThread())
.onErrorResumeNext(Observable.<CameraPosition>empty())
.debounce(1, TimeUnit.SECONDS)
.subscribe(cameraPosition -> {
final LatLngBounds item = map.getProjection().getVisibleRegion().latLngBounds;
homeActionBarActivity.getNMB().getRide().list(
item.southwest.latitude,
item.southwest.longitude,
item.northeast.latitude,
item.northeast.longitude)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.onErrorResumeNext(Observable.<List<Ride>>empty())
.subscribe(new Action1<List<Ride>>() {
#Override
public void call(List<Ride> rides) {
clearRidePointsFromMap();
for (Ride ride : rides) {
if (isAdded())
addRideStartPointToMap(ride);
}
}
});
});
As you can see, I am forcing to use the MainThread for both (subscribeOn and observeOn) but I still get this error "Not on the main thread".
Here the stacktrace:
01-27 10:59:24.049 3049-3066/com.nousmotards.android E/AndroidRuntime﹕ FATAL EXCEPTION: RxComputationThreadPool-2
Process: com.nousmotards.android, PID: 3049
java.lang.IllegalStateException: Exception thrown on Scheduler.Worker thread. Add `onError` handling.
at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:52)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:864)
Caused by: rx.exceptions.OnErrorNotImplementedException: Not on the main thread
at rx.Observable$31.onError(Observable.java:7134)
at rx.observers.SafeSubscriber._onError(SafeSubscriber.java:154)
at rx.observers.SafeSubscriber.onError(SafeSubscriber.java:111)
at rx.observers.SafeSubscriber.onNext(SafeSubscriber.java:137)
at rx.observers.SerializedObserver.onNext(SerializedObserver.java:159)
at rx.observers.SerializedSubscriber.onNext(SerializedSubscriber.java:81)
at rx.internal.operators.OperatorDebounceWithTime$DebounceState.emit(OperatorDebounceWithTime.java:128)
at rx.internal.operators.OperatorDebounceWithTime$1$1.call(OperatorDebounceWithTime.java:72)
at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:47)
            at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
            at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:864)
Caused by: java.lang.IllegalStateException: Not on the main thread
at com.google.k.a.cl.b(Unknown Source)
at com.google.maps.api.android.lib6.c.ca.a(Unknown Source)
at com.google.maps.api.android.lib6.c.el.l(Unknown Source)
at com.google.android.gms.maps.internal.l.onTransact(SourceFile:312)
at android.os.Binder.transact(Binder.java:361)
at com.google.android.gms.maps.internal.IGoogleMapDelegate$a$a.getProjection(Unknown Source)
at com.google.android.gms.maps.GoogleMap.getProjection(Unknown Source)
at com.nousmotards.android.fragments.home.MapFragment.lambda$onViewCreated$33(MapFragment.java:117)
at com.nousmotards.android.fragments.home.MapFragment.access$lambda$0(MapFragment.java)
at com.nousmotards.android.fragments.home.MapFragment$$Lambda$1.call(Unknown Source)
at rx.Observable$31.onNext(Observable.java:7139)
at rx.observers.SafeSubscriber.onNext(SafeSubscriber.java:130)
            at rx.observers.SerializedObserver.onNext(SerializedObserver.java:159)
            at rx.observers.SerializedSubscriber.onNext(SerializedSubscriber.java:81)
            at rx.internal.operators.OperatorDebounceWithTime$DebounceState.emit(OperatorDebounceWithTime.java:128)
            at rx.internal.operators.OperatorDebounceWithTime$1$1.call(OperatorDebounceWithTime.java:72)
            at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:47)
            at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
            at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:864)
Do you have any idea ?
Note: if I get out map.setOnCameraChangeListerner(...) from Observable.create(...) it works correctly.

Ok it seems that is (probably) due to the RxJava internal on how it is managed to pass objects from subscriber to observers. I fix my problem by simply getting LatLngBounds inside the subscriber and not the observer.
Observable.create(new Observable.OnSubscribe<LatLngBounds>() {
#Override
public void call(Subscriber<? super LatLngBounds> subscriber) {
if (!subscriber.isUnsubscribed()) {
map.setOnCameraChangeListener(cameraPosition ->
subscriber.onNext(map.getProjection().getVisibleRegion().latLngBounds));
}
}
}).subscribeOn(AndroidSchedulers.mainThread())
.observeOn(AndroidSchedulers.mainThread())
.onErrorResumeNext(Observable.<LatLngBounds>empty())
.debounce(1, TimeUnit.SECONDS)
.subscribe(item -> {
homeActionBarActivity.getNMB().getRide().list(
item.southwest.latitude,
item.southwest.longitude,
item.northeast.latitude,
item.northeast.longitude)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.onErrorResumeNext(Observable.<List<Ride>>empty())
.subscribe(new Action1<List<Ride>>() {
#Override
public void call(List<Ride> rides) {
clearRidePointsFromMap();
for (Ride ride : rides) {
if (isAdded())
addRideStartPointToMap(ride);
}
}
});
});
Hope this will help :)

Related

why component == null in dagger 2?

It seems that it just created AppComponent and then delete it. In other my projects it's works correctly. Why appComponent become null and how to make it working ?
App.class
public class App extends Application {
private static AppComponent appComponent;
#Override
public void onCreate() {
super.onCreate();
buildGraphAndInject();
}
public static AppComponent getAppComponent() {
if(appComponent == null) {
Log.d("getter", "null");
}
return appComponent;
}
public void buildGraphAndInject() {
appComponent = DaggerAppComponent.builder()
.appModule(new AppModule(this))
.build();
appComponent.inject(this);
if(appComponent == null) {
Log.d("build", "null");
}
}
}
call from Activity
#Override
public void setupComponent(AppComponent appComponent) {
mComponent = DaggerMainComponent.builder()
.appComponent(App.getAppComponent())
.build();
mComponent.inject(this);
}
AppComponent
#Component(modules = {AppModule.class})
public interface AppComponent {
void inject(App app);
}
result
04-02 02:16:23.544 32016-32016/exp.privatebank D/getter: null
04-02 02:16:23.569 32016-32016/exp.privatebank E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{exp.privatebank/exp.privatebank.view.activity.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
at android.app.ActivityThread.access$700(ActivityThread.java:159)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at dagger.internal.Preconditions.checkNotNull(Preconditions.java:32)
at exp.privatebank.di.DaggerMainComponent$Builder.appComponent(DaggerMainComponent.java:110)
at exp.privatebank.view.activity.MainActivity.setupComponent(MainActivity.java:58)
at exp.privatebank.common.BaseActivity.onCreate(BaseActivity.java:19)
at exp.privatebank.view.activity.MainActivity.onCreate(MainActivity.java:38)
at android.app.Activity.performCreate(Activity.java:5372)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349) 
at android.app.ActivityThread.access$700(ActivityThread.java:159) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:176) 
at android.app.ActivityThread.main(ActivityThread.java:5419) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:525) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862) 
at dalvik.system.NativeStart.main(Native Method) 

Expected begin_object but was string at line 1 column 1

I am developing an android application,In that,I have a task to update profile image when I am try to update image I am getting that error,I don't know what is the root cause of that error please help me how to fix that.
My log is below
Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:200)
at com.google.gson.Gson.fromJson(Gson.java:810)
at com.google.gson.Gson.fromJson(Gson.java:775)
at com.google.gson.Gson.fromJson(Gson.java:724)
at com.ringee.app.ImageUploadActivity$5$2.doInBackground(ImageUploadActivity.java:215)
at com.ringee.app.ImageUploadActivity$5$2.doInBackground(ImageUploadActivity.java:206)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:387)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:189)
            at com.google.gson.Gson.fromJson(Gson.java:810)
            at com.google.gson.Gson.fromJson(Gson.java:775)
            at com.google.gson.Gson.fromJson(Gson.java:724)
            at com.ringee.app.ImageUploadActivity$5$2.doInBackground(ImageUploadActivity.java:215)
            at com.ringee.app.ImageUploadActivity$5$2.doInBackground(ImageUploadActivity.java:206)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
My code is below
{
new AsyncTask<Void, Void, Bitmap>() {
#Override
protected Bitmap doInBackground(Void... arg0) {
MediaMO mediaMO1 = new MediaMO();
mediaMO1.setRingeeUserId(userMO.getRingeeUserId());
mediaMO1.setIsType(Constants.IS_TYPE_PROFILE_IMAGE);
String mediaMo = mediaDelegates.updateFileToServer(mediaMO1, context, imgFile);
// String mediaMo = mediaDelegates.updateFileToServer(mediaMO, context, imgFile);
if (!mediaMo.equals("null")) {
//I am getting that error here
mediaMO = gson.fromJson(mediaMo, new TypeToken<MediaMO>() {
}.getType());
try {
URL url = new URL(mediaMO.getFileSrcLink());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
} catch (IOException e) {
Log.i(Constants.TAG, e.toString());
}
}
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_action_user);
return largeIcon;
}
#Override
protected void onPostExecute(Bitmap myBitmap) {
prgDialog.cancel();
imageView.setImageBitmap(myBitmap);
}
}.execute(null, null, null);
}
my json is
{"UserId":1,"mediaId":0,"isType":1,"isDelete":0}

BufferedRead runtime crash

My app crash when encounters BufferedReader operation. Ive tried to implement the code inside an asyncTask classe, because ive read that the crash is caused by the ui thread, but nothing has changed.
public class URLConnectionReader extends AsyncTask<URL, Void, String> {
String result = null;
#Override
protected String doInBackground(URL... params) {
String result = null;
URL url = (params[0]);
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(
url.openStream()
)
);
}catch (IOException e){
e.printStackTrace();
}
return result;
}
}
Logs
03-02 13:28:43.215 25186-25186/com.example.jsonreader E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.jsonreader, PID: 25186
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jsonreader/com.example.jsonreader.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:323)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:190)
at java.net.URL.openStream(URL.java:470)
at com.example.jsonreader.URLConnectionReader.doInBackground(URLConnectionReader.java:38)
at com.example.jsonreader.MainActivity.onCreate(MainActivity.java:27)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
MainActivity code
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
URL address = new URL("http://www.youth-stories.com/api/all.php");
URLConnectionReader reader = new URLConnectionReader();
String result = reader.doInBackground(address);
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
}catch (IOException e){
e.printStackTrace();
}
i solved the problem to get back data using the .get instruction
String result = reader.execute(address).get();

Volley Request Queue NullPointerException

I am trying to use the Volley library to query an xml api on the web with a search query provided by the user through a SearchWidget.
Whenever I enter a search string, the app crashes with a NullPointerException on adding the StringRequest to the RequestQueue.
Why is this happening?
I am already using Volley with a singleton pattern, as recommended in the Android Developer Guide.
Here is my search() function in the MainActivity.
public static final String TAG = "MYAPPTAG"
private RequestQueue mRequestQueue;
...
protected void onCreate(Bundle savedInstanceState) {
...
// Handle search intent
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
search(query);
}
volley = MySingleton.getInstance(getApplicationContext());
mRequestQueue = volley.getRequestQueue();
}
...
private void search(String query) {
String xml = null;
String url = "http://www.acme.com/example.php?query=" + query;
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
stringRequest.setTag(TAG);
mRequestQueue
.add(stringRequest); // the exception fires here
}
...
See below for the stack trace.
02-22 23:08:50.636 9856-9856/com.example.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.app, PID: 9856
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.app/com.example.app.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2212)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2271)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5146)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.app.MainActivity.search(MainActivity.java:121)
at com.example.app.MainActivity.onCreate(MainActivity.java:83)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2271)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5146)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
            at dalvik.system.NativeStart.main(Native Method)
You are firing off a search before you've set the requestqueue from singleton.
So onCreate, you check for the Intent and then start a search before you've got a handle on the volley singleton and, in turn, the requestqueue. Try moving the volley code before the Intent check, like this:
volley = MySingleton.getInstance(getApplicationContext());
mRequestQueue = volley.getRequestQueue();
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
search(query);
}

Check if Internet Connection Is Active In Android

i am trying to check for internet connection in my application.
first, i am checking if wifi or mobile data is on, then i am checking if there is an active internet connection.
what i am currently doing:
public class ConnectivityReceiver extends BroadcastReceiver {
String TAG="ConnectivityReceiver";
public static boolean hasInternetAccess() {
try {
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 204 &&
urlc.getContentLength() == 0);
} catch (IOException e) {
}
return false;
}
#Override
public void onReceive(Context arg0, Intent intent) {
String action = intent.getAction();
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,false);
if(noConnectivity){
try{
TaskListAndOptionsActivity.item3.setIcon(R.drawable.ic_action_network_nowifi);
}
catch(Exception e)
{
}
}
else
{
Boolean status = hasInternetAccess();
if(status==true)
{
try{
TaskListAndOptionsActivity.item3.setIcon(R.drawable.ic_action_network_wifi);
}
catch(Exception e)
{
}
}
else
{
try{
TaskListAndOptionsActivity.item3.setIcon(R.drawable.ic_action_network_nowifi);
}
catch(Exception e)
{
}
}
}
}
but i am getting the following error:
java.lang.RuntimeException: Unable to start receiver connectionchecker.ConnectivityReceiver: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2668)
at android.app.ActivityThread.access$1800(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1384)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5653)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1166)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:390)
at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:343)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:289)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
at connectionchecker.NetworkUtil.hasInternetAccess(NetworkUtil.java:21)
at connectionchecker.ConnectivityReceiver.onReceive(ConnectivityReceiver.java:46)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2653)
            at android.app.ActivityThread.access$1800(ActivityThread.java:172)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1384)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5653)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
            at dalvik.system.NativeStart.main(Native Method)
You are trying to connect to the network in UI thread which is not allowed. to check for active internet connection use following method.
public boolean isConnected() {
ConnectivityManager manager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
return true;
} else {
return false;
}
}
Once you receive the value, if it is true proceed with network operation. Else display the user a proper error message.
Caused by: android.os.NetworkOnMainThreadException
You need to perform network operation not on UIthread.
Sounds like you might need to use the getActiveNetworkInfo() call. There is a few posts on stackoverflow already that document it extensively so rather than repeat those have a look at these:
Detect whether there is an Internet connection available on Android

Categories