Java NetworkOnMainThreadException read csv file from URL [duplicate] - java

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("");

Related

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

Error getting content from .txt file from URL

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();
}

Android tcp connection to computer

I am new to android.
I tried to build an application which sends a string from android mobile to a java client on my pc.
here is the server side:
public class Ser {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(12345);
Socket s = ss.accept();
InputStream is = s.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
System.out.println("message received from server is :");
String ms = br.readLine();
System.out.println("" + ms);
}
}
and here is the client side:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Socket s= null;
try {
s = new Socket("192.168.0.102",12345);
OutputStream os=s.getOutputStream();
PrintWriter pw=new PrintWriter(os);
pw.println("Hey!!! I am from client side ");
pw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
but this is giving the following error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ankitanand.udp/com.example.ankitanand.udp.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2122)
at android.app.ActivityThread.access$600(ActivityThread.java:140)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1228)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4895)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
at libcore.io.IoBridge.connect(IoBridge.java:112)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.Socket.startupSocket(Socket.java:566)
at java.net.Socket.tryAllAddresses(Socket.java:127)
at java.net.Socket.<init>(Socket.java:177)
at java.net.Socket.<init>(Socket.java:149)
at com.example.ankitanand.udp.MainActivity.onCreate(MainActivity.java:30)
at android.app.Activity.performCreate(Activity.java:5163)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2061)
            
The ip of my pc is 192.168.0.102
Also i have used the following permission in the manifest file
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
You can't do network stuff on the Main thread. Try using an AsyncTask
Take also a look on this page about Network on Main Thread Exeption.
With that your code will work.

java.lang.NoClassDefFoundError

i was implmenting a pdf reader in my project when i got the following error..
E/AndroidRuntime(1495): FATAL EXCEPTION: main
E/AndroidRuntime(1495): Process: com.example.testqstn, PID: 1495
E/AndroidRuntime(1495): java.lang.NoClassDefFoundError: com.questionpoint.pdf.Pdf
E/AndroidRuntime(1495): at com.question_point.main.Question_Point_Main.openPdfIntent(Question_Point_Main.java:272)
E/AndroidRuntime(1495): at com.question_point.main.Question_Point_Main.CopyReadAssets(Question_Point_Main.java:266)
E/AndroidRuntime(1495): at com.question_point.main.Question_Point_Main.pdfSelection(Question_Point_Main.java:128)
E/AndroidRuntime(1495): at com.question_point.main.Question_Point_Main$2.onClick(Question_Point_Main.java:104)
E/AndroidRuntime(1495): at android.view.View.performClick(View.java:4438)
E/AndroidRuntime(1495): at android.view.View$PerformClick.run(View.java:18422)
E/AndroidRuntime(1495): at android.os.Handler.handleCallback(Handler.java:733)
E/AndroidRuntime(1495): at android.os.Handler.dispatchMessage(Handler.java:95)
E/AndroidRuntime(1495): at android.os.Looper.loop(Looper.java:136)
E/AndroidRuntime(1495): at android.app.ActivityThread.main(ActivityThread.java:5017)
E/AndroidRuntime(1495): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(1495): at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime(1495): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
E/AndroidRuntime(1495): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
E/AndroidRuntime(1495): at dalvik.system.NativeStart.main(Native Method)
I/Process(1495): Sending signal. PID: 1495 SIG: 9
i had imported a project to my code.. my library file is named libs, and i have repeatedly cleaned my project.. but still the error persists.. Thanks in advance..
The code that leads to error
public void CopyReadAssets(String url) {
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), url);
try {
in = assetManager.open(url);
out = openFileOutput(file.getName(),
Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
String path = "file://" + getFilesDir() + "/"+url;
openPdfIntent(path);
}
private void openPdfIntent(String path) {
// TODO Auto-generated method stub
try {
final Intent intent = new Intent(Question_Point_Main.this, Pdf.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, path);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
Try these steps:
Step 1: Create a folder "lib", and copy all third-party jars here;
Step 2: Add these jars to build path;
Step 3: Use the folder as Source Folder(shown below).
Maybe you just forgot the underscore and you meant com.question_point.pdf.Pdf?
It would be easier to tell if you could post the relevant code where you make the call that leads to the Exception.

KitKat Connection from URL get NullPointerException in AsyncTask

i'm new in java and android programming but i accepted a challenge launched by a friend and now i have to work hard.
I finally managed to have this type of activity working with AsyncTask but it seems to work well on all android but not on 4.4.2 KitKat.
The problem seems to be on url.openConnection and i tried many times to change the way in wich i do it but i haven't had positive results...
I have only to read file from an URL
This is my class code:
public class MenuActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
new HttpTask().execute();
}
public final class HttpTask
extends
AsyncTask<String/* Param */, Boolean /* Progress */, String /* Result */> {
private HttpClient mHc = new DefaultHttpClient();
#Override
protected String doInBackground(String... params) {
publishProgress(true);
InputStream inputstream = null;
URL url = null;
try {
url = new URL("http://somesite/prova.txt");
} catch (MalformedURLException e) {
e.printStackTrace();
}
assert url != null;
URLConnection connection = null;
try {
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputstream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
ByteArrayOutputStream bytearryoutputstream = new ByteArrayOutputStream();
int i;
try {
i = inputstream.read();
while (i != -1) {
bytearryoutputstream.write(i);
i = inputstream.read();
}
inputstream.close();
} catch (IOException e) {
e.printStackTrace();
}
return bytearryoutputstream.toString();
}
#Override
protected void onProgressUpdate(Boolean... progress) {
}
#Override
protected void onPostExecute(String result) {
StringBuilder nuovafrase=new StringBuilder("");
String[] frasone=result.split("\n");
ListView listView = (ListView)findViewById(R.id.listViewDemo);
ArrayAdapter<String> arrayAdapter;
arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.rowmenu, R.id.textViewList, frasone);
listView.setAdapter(arrayAdapter);
}
}
}
And this is the Logcat...
03-11 17:49:37.955 1277-1294/com.example.appsb.app W/System.err﹕ atjava.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-11 17:49:37.955 1277-1294/com.example.appsb.app W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at java.lang.Thread.run(Thread.java:841)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at libcore.io.Posix.getaddrinfo(Native Method)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ ... 18 more
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ Caused by: libcore.io.ErrnoException: getaddrinfo failed: EACCES (Permission denied)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ ... 21 more
03-11 17:49:37.963 1277-1294/com.example.appsb.app W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0xa4d69b20)
03-11 17:49:37.963 1277-1294/com.example.appsb.app E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.example.appsb.app, PID: 1277
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
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.NullPointerException
at com.example.appsb.app.MenuActivity$HttpTask.doInBackground(MenuActivity.java:74)
at com.example.appsb.app.MenuActivity$HttpTask.doInBackground(MenuActivity.java:33)
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)
There is a Caused by: java.lang.NullPointerException but i cannot understand why...
Thanks
It could be caused by the inputstream being null. inputstream will only be initialized if the response code is OK. So you need to check what response code is being returned. If it is not causing the error, I'd still add some code for if the response code is not OK. You don't want your app to crash if it can't connect. You should at least display a helpful error message
Example:
else{
showErrorMsg();
return null;
}
Catch FileNotFoundException when trying inputstream.read();
try {
i = inputstream.read();
while (i != -1) {
bytearryoutputstream.write(i);
i = inputstream.read();
}
inputstream.close();
} catch (FileNotFoundException e) {
Log.e("MyTag","Handling empty page...");
} catch (IOException e) {
Log.e("MyTag",e.toString());
}

Categories