URL scoreU = null;
try {
scoreU = new URL("http://m.uploadedit.com/b044/1422550899503.txt");
} catch (MalformedURLException e) {
e.printStackTrace();
}
BufferedReader in = null;
try {
in = new BufferedReader(
new InputStreamReader(
scoreU.openStream()));
} catch (IOException e) {
e.printStackTrace();
}
String inputLine;
try {
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
That's my code related to getting the text from the URL. It's the first time I have done this and I cannot understand my mistake. (I had to surround almost everything with a try/catch .
ERROR:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.wc.gap.worldcupfixture/com.wc.gap.worldcupfixture.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.wc.gap.worldcupfixture.MainActivity.onCreate(MainActivity.java:102)
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)
new InputStreamReader(scoreU.openStream()));
Android doesn't allow network requests on the main thread as it can cause UI unresponsiveness. Instead you have to do the work on a background thread, but this is pretty easy with an AsyncTask, for example:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
// Start the task here
new URLDataLoader().execute(theURL);
}
private class URLDataLoader extends AsyncTask<URL, Void, String> {
#Override
protected String doInBackground(URL... params) {
URL theURL = params[0];
// Do your network stuff here to get the data
return theData;
}
#Override
protected void onPostExecute(String data) {
// Use the data here
}
}
}
Use this code:-
try {
URL url = new URL("http://m.uploadedit.com/b044/1422550899503.txt");
URLConnection urlConnection = url.openConnection();
HttpURLConnection connection = null;
connection = (HttpURLConnection) urlConnection;
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String urlString = "";
String current;
while ((current = in.readLine()) != null) {
urlString += current;
}
System.out.println(urlString);
} catch (IOException e) {
e.printStackTrace();
}
Related
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 5 years ago.
Hello i am using android studio to create an App and i have encountered an error which is proving hard to resolve by myself. All i want to do is read a CSV file from a url and for each row add the values to a map marker. I can easily read from a file and add the to my markers, but this url csv read is proving a challenge for me :(. What is my mistake please or even better can it be simplified too.
HttpURLConnection conn = null;
try {
URL url = new URL("http://www.free-map.org.uk/course/mad/ws/get.php?username=user002&format=csv");
conn = (HttpURLConnection) url.openConnection();
InputStream in = conn.getInputStream();
if(conn.getResponseCode() == 200)
{
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String inputLine;
while ((inputLine = br.readLine()) != null) {
String[] comps = inputLine.split(",");
if (comps.length == 5) {
OverlayItem currentItem = new OverlayItem(comps[0], comps[2], new GeoPoint(Double.parseDouble(comps[4]), Double.parseDouble(comps[3])));
pois.addItem(currentItem);
}
}
}
}catch (IOException e){
new AlertDialog.Builder(this).setMessage("ERROR: "+e).show();
}
finally
{
if(conn!=null)
conn.disconnect();
}
I have this code placed in my on Resume() to test if it is working if that helps. and these are the errors displayed in Logcat.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.edwin.mapping, PID: 2048
java.lang.RuntimeException: Unable to resume activity {com.example.edwin.mapping/com.example.edwin.mapping.HelloMap}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2788)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
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:292)
at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:179)
at com.example.edwin.mapping.HelloMap.onResume(HelloMap.java:158)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1192)
at android.app.Activity.performResume(Activity.java:5310)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Application terminated.
use an Async Task to perform the network operation. Do not run it on UI thread.
For example:
private class ReadFile extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection conn = null;
try {
URL url = new URL("http://www.free-map.org.uk/course/mad/ws/get.php?username=user002&format=csv");
conn = (HttpURLConnection) url.openConnection();
InputStream in = conn.getInputStream();
if(conn.getResponseCode() == 200)
{
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String inputLine;
while ((inputLine = br.readLine()) != null) {
String[] comps = inputLine.split(",");
if (comps.length == 5) {
OverlayItem currentItem = new OverlayItem(comps[0], comps[2], new GeoPoint(Double.parseDouble(comps[4]), Double.parseDouble(comps[3])));
pois.addItem(currentItem);
}
}
}
}catch (Exception e){
Log.e("Error, e.toString());
}
finally
{
if(conn!=null)
conn.disconnect();
}
return null;
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {}
}
Now call it using:
new ReadFile().execute("");
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}
I'm trying to get a screenshot from a fragment, but seems that when I do
bitmap = view.getDrawingCache(); it returns null. Does anyone knows why is this happening and how can I fix this?
here is my code:
public void takeScreenshot(View view) {
OutputStream output;
view = view.getRootView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache(true);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath + "/"
+ getString(R.string.app_name) + "/");
dir.mkdirs();
File file = new File(dir, getString(R.string.app_name) + ".jpg");
bitmap = view.getDrawingCache();
try {
output = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 80, output);
output.flush();
output.close();
Log.d(TAG, "screenshot saved");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
and calling the method
takeScreenshot(getActivity().findViewById(R.id.fragment_container));
and here is the logCat output:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.contractfit/com.contractfit.activities.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
at android.app.ActivityThread.access$900(ActivityThread.java:175)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5602)
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:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.contractfit.fragments.BaseFragment.takeScreenshot(BaseFragment.java:532)
at com.contractfit.fragments.MainFragment.init(MainFragment.java:211)
at com.contractfit.fragments.MainFragment.onCreateView(MainFragment.java:116)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:551)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1177)
at android.app.Activity.performStart(Activity.java:5461)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2386)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
at android.app.ActivityThread.access$900(ActivityThread.java:175)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5602)
at java.lang.reflect.Method.invokeNative(Native Method)
Consider doing this like Instrumentation test cases do it, your code is close but differs a bit.
From https://android.googlesource.com/platform/external/droiddriver/+/367267b/src/io/appium/droiddriver/instrumentation/InstrumentationUiDevice.java
Get root view (if it's public):
context.getDriver().getRootElement().getRawElement()));
Take screenshot
public Bitmap call() {
Bitmap screenshot;
rootView.destroyDrawingCache();
rootView.buildDrawingCache(false);
Bitmap drawingCache = rootView.getDrawingCache();
int[] xy = new int[2];
rootView.getLocationOnScreen(xy);
if (xy[0] == 0 && xy[1] == 0) {
screenshot = Bitmap.createBitmap(drawingCache);
} else {
Canvas canvas = new Canvas();
Rect rect = new Rect(0, 0, drawingCache.getWidth(), drawingCache.getHeight());
rect.offset(xy[0], xy[1]);
screenshot =
Bitmap.createBitmap(rect.width() + xy[0], rect.height() + xy[1], Config.ARGB_8888);
canvas.setBitmap(screenshot);
canvas.drawBitmap(drawingCache, null, new RectF(rect), null);
canvas.setBitmap(null);
}
rootView.destroyDrawingCache();
return screenshot;
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();
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