Parsing a text file in android from an HTML - java

So I have been working on this for a bit and hit a brick wall. It keeps giving me a fatal error when it start to process.
So basically I want to read in a text file off the internet and then parse it so I can start to break that apart and use a JSON parser to deal with JSON data. But that further down the line (and i have the part built). I just am having trouble with the connection and downloading of the data. I just want to read in the text file and then print it out again.
Thank you for any help with this.
This is what it gives me
01-26 15:11:48.373 1958-1958/com.example.mmillar.urljsonparser I/art: Not late-enabling -Xcheck:jni (already on)
01-26 15:11:48.556 1958-1958/com.example.mmillar.urljsonparser D/HTML P1:: http://textfiles.com/100/914bbs.txt
01-26 15:11:48.556 1958-1958/com.example.mmillar.urljsonparser D/HTML P2:: http://textfiles.com/100/914bbs.txt
01-26 15:11:48.557 1958-1958/com.example.mmillar.urljsonparser D/HTML inJSON:: http://textfiles.com/100/914bbs.txt
01-26 15:11:48.569 1958-1958/com.example.mmillar.urljsonparser D/Status:: Connection Opened
01-26 15:11:48.569 1958-1958/com.example.mmillar.urljsonparser D/Status:: Closing connection
01-26 15:11:48.569 1958-1958/com.example.mmillar.urljsonparser D/AndroidRuntime: Shutting down VM
01-26 15:11:48.570 1958-1958/com.example.mmillar.urljsonparser E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mmillar.urljsonparser, PID: 1958
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mmillar.urljsonparser/com.example.mmillar.urljsonparser.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
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:382)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:332)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:199)
at com.example.mmillar.urljsonparser.JSONParser.getStream(JSONParser.java:40)
at com.example.mmillar.urljsonparser.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
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:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
01-26 15:11:53.474 1958-1958/? I/Process: Sending signal. PID: 1958 SIG: 9
So I'm a bit lost to where this is going wrong. I think I have everything set up and going good. Like the inputstream, bufferreader and all. So here is what I have.
This is the Parser program
public class JSONParser extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... inputUrl) {
getStream(inputUrl[0]);
return null;
}
public void getStream(String urlString)
{
Log.d("HTML inJSON: ", urlString );
//variables for the connection and downloading the JSON data
URL url = null;
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
url = new URL(urlString);
urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
Log.d("Status:","Connection Opened");
//read in the data
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
//build the data for parsing
StringBuilder myString = new StringBuilder();
String line;
while((line = br.readLine()) !=null)
{
myString.append(line);
}
Log.d("Status:"," JSON loaded into string");
Log.d("Total:", myString.toString());
} catch (IOException e) {
e.printStackTrace();
}finally {
if (urlConnection != null)
{
//close the connection
urlConnection.disconnect();
Log.d("Status:", " Closing connection");
}
}
}
}
And here is the main program I just run the thing because I just want to output from the file to the console I just want to make sure it works.
public class MainActivity extends AppCompatActivity {
//http://textfiles.com/100/914bbs.txt
private String testHtml = "http://textfiles.com/100/914bbs.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("HTML P1: ", testHtml );
JSONParser jp = new JSONParser();
Log.d("HTML P2: ", testHtml );
jp.getStream(testHtml);
Log.d("HTML P3: ", testHtml);
}

instead of using
jp.getStream(testHtml);
use
jp.execute("stream url here");
Currently you are trying to create a function in your Asynctask, but are not leveraging the use of AsyncTask. It still tries to make a HttpConnection on the mainThread, and that throws the exception.

Related

Why can't filereader find my file? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
My app won't launch and points to a Null Pointer Exception on my FileReader fr. I initialized it as null to prevent a "Variable may not have been initialized" error. I know the file I want it to use is there under downloads. The file is also inside the main project folder and putting just "academiccalendar.json" does not work either.
My main activity:
public class MainActivity extends AppCompatActivity {
Event[] mobileArray;
Gson gson = new Gson();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BufferedReader br;
FileReader fr = null;
try {
fr = new FileReader("C:/Users/Ali/Downloads/academiccalendar.json");
}
catch (FileNotFoundException e){
e.printStackTrace();
}
br = new BufferedReader(fr);
//br = new BufferedReader(new FileReader("C:/Users/Ali/Downloads/academiccalendar.json"));
mobileArray = gson.fromJson(br, Event[].class);
My logcat output:
12-31 20:06:37.368 9449-9449/com.example.test.testassigment E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test.testassigment/com.example.test.testassigment.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1967)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
at android.app.ActivityThread.access$600(ActivityThread.java:127)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4511)
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:976)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:743)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:64)
at java.io.BufferedReader.<init>(BufferedReader.java:92)
at java.io.BufferedReader.<init>(BufferedReader.java:80)
at com.example.test.testassigment.MainActivity.onCreate(MainActivity.java:42)
at android.app.Activity.performCreate(Activity.java:4486)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1052)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1931)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992) 
at android.app.ActivityThread.access$600(ActivityThread.java:127) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4511) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511)
"C:/Users/Ali/Downloads/academiccalendar.json"
That is a path on your Windows PC. Windows uses drive letters.
Your Android app cannot read files from your PC of course. Or from mine ;-).
I suppose your Android app wants to read a file which is on your Android device.
Try to determine the file on the file system of your Android device.
Because of your path defination. You can use this:
fr = new FileReader("C:\\Users\\Ali\\Downloads\\academiccalendar.json");

Android Dropbox API v1 upload file and get shared link of this file

I have uploaded file and when I try to get the shared link then it gives NullPointerException.
FileInputStream fis = new FileInputStream(mFile);
String path = mPath + mFile.getName();
DropboxAPI.Entry response = mApi.putFile(path, fis,
mFile.length(), null, new ProgressListener() {
#Override
public long progressInterval() {
// Update the progress bar every half-second or so
return 500;
}
#Override
public void onProgress(long bytes, long total) {
publishProgress(bytes);
}
});
Log.i("DbExampleLog", "The uploaded file's rev is: " + response.rev);
if (response != null) {
mErrorMsg=response.path;
Log.e("DbExampleLog", "*****"+response.path+" The uploaded file's rev is: " + response.rev);
DropboxAPI.DropboxLink shareLink = mApi.share(response.path);
Log.e("DbExampleLog", "*****"+shareLink+" The uploaded file's rev is: " + response.rev);
if(shareLink!=null) {
if(shareLink.url!=null) {
Log.e("Null error URL*****",""+shareLink.url);
Log.e("Null error URL*****",""+getShareURL(shareLink.url));
String shareAddress = getShareURL(shareLink.url).toString();
Log.e("DbExampleLog", "URL -" + shareAddress + "*****" + response.path + " The uploaded file's rev is: " + response.rev);
}
else
Log.e("Null error URL*****",""+shareLink.url);
}
else{
Log.e("Null error*****",""+shareLink);
}
return true;
}
It returns like -
12-05 12:09:09.207 7335-7502/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/DbExampleLog: *****/1480919937073.jpg The uploaded file's rev is: 2ef4a7ca38e
12-05 12:09:10.966 7335-7502/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/DbExampleLog: *****com.dropbox.client2.DropboxAPI$DropboxLink#d9d5da1 The uploaded file's rev is: 2ef4a7ca38e
12-05 12:09:10.966 7335-7502/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/Null error URL*****: https://db.tt/ru6e39XK0
12-05 12:09:12.457 7335-7502/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/Null error URL*****: null
12-05 12:09:13.520 7335-7502/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.trucker.gtd.satyaki.dropboxintegrationapiv1, PID: 7335
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:318)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
at com.trucker.gtd.satyaki.dropboxintegrationapiv1.UploadFile.doInBackground(UploadFile.java:147)
at com.trucker.gtd.satyaki.dropboxintegrationapiv1.UploadFile.doInBackground(UploadFile.java:63)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 
at java.lang.Thread.run(Thread.java:761) 
12-05 12:09:13.645 1248-1248/? E/EGL_emulation: tid 1248: eglCreateSyncKHR(1641): error 0x3004 (EGL_BAD_ATTRIBUTE)
12-05 12:09:13.796 2071-2205/com.android.launcher3 E/EGL_emulation: tid 2205: eglSurfaceAttrib(1146): error 0x3009 (EGL_BAD_MATCH)
12-05 12:09:14.006 1530-1640/system_process E/EGL_emulation: tid 1640: eglSurfaceAttrib(1146): error 0x3009 (EGL_BAD_MATCH)
12-05 12:09:14.304 7335-7335/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/WindowManager: android.view.WindowLeaked: Activity com.trucker.gtd.satyaki.dropboxintegrationapiv1.Main has leaked window DecorView#3bf9cac[] that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:417)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:331)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
at android.app.Dialog.show(Dialog.java:316)
at android.app.AlertDialog$Builder.show(AlertDialog.java:1112)
at com.dropbox.client2.android.AuthActivity.checkAppBeforeAuth(AuthActivity.java:284)
at com.dropbox.client2.android.AndroidAuthSession.startAuthentication(AndroidAuthSession.java:213)
at com.trucker.gtd.satyaki.dropboxintegrationapiv1.Main.onActivityResult(Main.java:132)
at android.app.Activity.dispatchActivityResult(Activity.java:6915)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4049)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
12-05 12:09:14.310 7335-7335/com.trucker.gtd.satyaki.dropboxintegrationapiv1 E/WindowManager: android.view.WindowLeaked: Activity com.trucker.gtd.satyaki.dropboxintegrationapiv1.Main has leaked window DecorView#e8ad10a[] that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:417)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:331)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
at android.app.Dialog.show(Dialog.java:316)
at com.trucker.gtd.satyaki.dropboxintegrationapiv1.UploadFile.<init>(UploadFile.java:98)
at com.trucker.gtd.satyaki.dropboxintegrationapiv1.Main.setLoggedIn(Main.java:144)
at com.trucker.gtd.satyaki.dropboxintegrationapiv1.Main.onResume(Main.java:168)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1269)
at android.app.Activity.performResume(Activity.java:6766)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3377)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3440)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1510)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Mainly in this particular line-
getShareURL(shareLink.url)
Please suggest me why this error occur, but yesterday using this code it worked.
UPDATE CODE ASKED BY Greg
String getShareURL(String strURL) {
URLConnection conn = null;
String redirectedUrl = null;
try {
URL inputURL = new URL(strURL);
conn = inputURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
System.out.println("Redirected URL: " + conn.getURL());
Log.e("Get Redirected URL",""+conn.getURL());
redirectedUrl = conn.getURL().toString();
is.close();
} catch (MalformedURLException e) {
Log.e("TAG", "Please input a valid URL");
} catch (IOException ioe) {
Log.e("TAG", "Can not connect to the URL");
}
return redirectedUrl;
}
This code taken from Share file in Dropbox

Android UnkownHostException on devices with a lower API level

When trying my app on lower api levels such as 15 or 19(on emulators and real devices), i get a UnknownHostException for a specific URL: http://jotihunt-api_v2.mysite123.nl/login mysite123 is fictional. But i don't get a UnknownHostException for other urls such as that of google . So i seems the URL is wrong, but on API level 22 for example i don't get this exception. I have a Internet Connection and i have the required permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I use this code to execute post/get requests to a web API:
#Override
protected List<WebResponse> doInBackground(WebRequest... params) {
ArrayList<WebResponse> responses = new ArrayList<>();
WebRequest current;
for(int i = 0; i < params.length; i++)
{
current = params[i];
try {
InetAddress address = InetAddress.getByName(current.getUrl().getHost());
Log.i("WebRequestTask", address.toString());
} catch (UnknownHostException exception) {
Log.e("WebRequestTask", exception.toString(), exception);
}
TRYCATCH:
try
{
if(current.getUrl() == null) break TRYCATCH;
HttpURLConnection connection = (HttpURLConnection)current.getUrl().openConnection();
switch (current.getMethod())
{
case WebRequestMethod.POST:
if(current.hasData())
{
connection.setDoOutput(true);
connection.setRequestMethod(WebRequestMethod.POST);
OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream());
streamWriter.write(current.getData());
streamWriter.flush();
streamWriter.close();
}
break;
}
InputStream response;
if(connection.getResponseCode() == 200)
{
/*
* Get the response stream.
* */
response = connection.getInputStream();
}
else
{
/*
* Get the error stream.
* */
response = connection.getErrorStream();
}
/**
* Read the stream.
* */
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response));
StringBuilder builder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
bufferedReader.close();
/**
* Create a response
* */
responses.add(new WebResponse(current, builder.toString(), connection.getResponseCode()));
current.setExecutionDate(new Date());
connection.disconnect();
}
catch(Exception e)
{
/**
* Print the stack trace
* */
e.printStackTrace();
/**
* Log a error.
* */
Log.e("WebRequestTask", e.toString(), e);
/**
* Add a response with as text the error message
* */
responses.add(new WebResponse(current, e.toString(), 0));
}
}
return responses;
}
The state of the objects: http://imgur.com/8ehGBUf
The creation and execution of the request:
WebRequest request = new WebRequest.Builder()
.setId(MY_REQUEST_ID)
.setMethod(WebRequestMethod.POST)
.setUrl(new UrlBuilder().append("http://jotihunt-api_v2.mysite123.nl/login").build())
.setData("sfsf")
.create();
request.executeAsync(new WebRequest.OnWebRequestCompletedCallback() {
#Override
public void onWebRequestCompleted(WebResponse response) {
Log.i("",response.getData());
}
});
This is the exception i get:
08-16 12:33:36.340 4277-4356/nl.rsdt.japp W/System.err: java.net.UnknownHostException: http://jotihunt-api_v2.mysite123.nl/login
08-16 12:33:36.342 4277-4356/nl.rsdt.japp W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:279)
08-16 12:33:36.344 4277-4356/nl.rsdt.japp W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
08-16 12:33:36.346 4277-4356/nl.rsdt.japp W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
08-16 12:33:36.348 4277-4356/nl.rsdt.japp W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
08-16 12:33:36.352 4277-4356/nl.rsdt.japp W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
08-16 12:33:36.355 4277-4356/nl.rsdt.japp W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197)
08-16 12:33:36.356 4277-4356/nl.rsdt.japp W/System.err: at com.rsdt.anl.WebRequestTask.doInBackground(WebRequestTask.java:53)
08-16 12:33:36.357 4277-4356/nl.rsdt.japp W/System.err: at com.rsdt.anl.WebRequestTask.doInBackground(WebRequestTask.java:21)
08-16 12:33:36.358 4277-4356/nl.rsdt.japp W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288)
08-16 12:33:36.359 4277-4356/nl.rsdt.japp W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
08-16 12:33:36.360 4277-4356/nl.rsdt.japp W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
08-16 12:33:36.365 4277-4356/nl.rsdt.japp W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
08-16 12:33:36.372 4277-4356/nl.rsdt.japp W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
08-16 12:33:36.373 4277-4356/nl.rsdt.japp W/System.err: at java.lang.Thread.run(Thread.java:848)
UPDATE
I can resolve the host with InetAdress, but it still doesn't work
UPDATE 2
I found similar issues after some more googling, it seems that underscores are not valid URLs characters.
Sources:
(i cannot include more than 2 links so i left the begin of the link out)
stackoverflow.com/questions/36074952/unknown-host-exception-using-emulator-and-httpurlconnection
code.google.com/p/android/issues/detail?id=37577
github.com/google/ExoPlayer/issues/239
I changed the hostname so that is doesn't contain a underscore, this resolved my issues. It seems that the DNS on older android versions does not support URLs with a underscore
Sources:
Similiar issue
http://code.google.com/p/android/issues/detail?id=37577

UrlConnection.getInputStream() returns an exception that is null in Java

I have the following java code
try {
String u = "http://webapi.com/demo.zip";
URL url = new URL(u);
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
}
catch (Exception e) {
Log.d('downloaderror', e.getMessage());
}
But for some reason, the InputStream is = ucon.getInputStream() causes an error and the catch block is fired. And when the catch block is fired, the value of e is null.
Does anyone konw what is wrong with my ucon.getInputStream() ? I know for a fact that http://webapi.com/demo.zip exists, because I'm able to download the file from my web browser.
EDIT
Here's the stack trace on ucon.getInputstream()
java.lang.Exception
at com.example.instantramenz.samplewebview.MainActivity$1.onClick(MainActivity.java:94)
at android.view.View.performClick(View.java:4633)
at android.view.View$PerformClick.run(View.java:19270)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
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)
i fixed the problem by putting this line of code before downloading the file:
android.os.StrictMode.ThreadPolicy policy = new android.os.StrictMode.ThreadPolicy.Builder().permitAll().build();
android.os.StrictMode.setThreadPolicy(policy);

Gson outputting com.google.gson.JsonSyntaxException: java.io.EOFException: End of input at line 1 column 501

I've been using Gson to parse JSON in an API to use in my app. This is an example of the JSON output:
{"getdashboarddata":{"version":"1.0.0","runtime":492.3939704895,"data":{"raw":{"personal":{"hashrate":0},"pool":{"hashrate":1705841},"network":{"hashrate":41430764.301,"esttimeperblock":94.464466565347,"nextdifficulty":578.78109116,"blocksuntildiffchange":1}},"personal":{"hashrate":0,"sharerate":"0.0000","sharedifficulty":0,"shares":{"valid":0,"invalid":0,"invalid_percent":0,"unpaid":0},"estimates":{"block":0,"fee":0,"donation":0,"payout":0}},"pool":{"info":{"name":"RAPIDHASH","currency":"DOGE"},"workers":2199,"hashrate":1.705841,"shares":{"valid":1866290,"invalid":15564,"invalid_percent":0.83,"estimated":1866214,"progress":100},"price":"0.00000073","difficulty":32,"target_bits":21},"system":{"load":[0.1,0.25,0.29]},"network":{"hashrate":41.430764301,"difficulty":911.23745057,"block":235378,"esttimeperblock":94.46,"nextdifficulty":578.78109116,"blocksuntildiffchange":1}}}}
This is the logcat:
05-25 17:12:00.230 24143-24159/io.kd.figgycity50.mpos.mposchecker E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: io.kd.figgycity50.mpos.mposchecker, PID: 24143
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: com.google.gson.JsonSyntaxException: java.io.EOFException: End of input at line 1 column 501
at com.google.gson.Gson.fromJson(Gson.java:813)
at com.google.gson.Gson.fromJson(Gson.java:768)
at com.google.gson.Gson.fromJson(Gson.java:717)
at com.google.gson.Gson.fromJson(Gson.java:689)
at io.kd.figgycity50.mpos.mposchecker.MainActivity$DownloadWebpageTask.doInBackground(MainActivity.java:77)
at io.kd.figgycity50.mpos.mposchecker.MainActivity$DownloadWebpageTask.doInBackground(MainActivity.java:64)
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.io.EOFException: End of input at line 1 column 501
at com.google.gson.stream.JsonReader.nextNonWhitespace(JsonReader.java:1377)
at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:471)
at com.google.gson.stream.JsonReader.skipValue(JsonReader.java:1209)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:170)
at com.google.gson.Gson.fromJson(Gson.java:803)
            at com.google.gson.Gson.fromJson(Gson.java:768)
            at com.google.gson.Gson.fromJson(Gson.java:717)
            at com.google.gson.Gson.fromJson(Gson.java:689)
            at io.kd.figgycity50.mpos.mposchecker.MainActivity$DownloadWebpageTask.doInBackground(MainActivity.java:77)
            at io.kd.figgycity50.mpos.mposchecker.MainActivity$DownloadWebpageTask.doInBackground(MainActivity.java:64)
            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)
This is the code that gets and parses the JSON:
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
String resp = null;
try {
resp = downloadUrl(urls[0]);
} catch (IOException e) {
resp = "{\"getdashboarddata\":{\"data\":{\"personal\":{\"hashrate\":0},\"pool\":{\"info\":{\"name\":\"SET POOL IN SETTINGS\",\"currency\":\"???\"},\"hashrate\":0,\"difficulty\":0},\"network\":{\"hashrate\":0,\"difficulty\":0}}}}";
}
Gson gson = new Gson();
Log.d("INFO", resp);
MPOSDashStruct data = gson.fromJson(resp, MPOSDashStruct.class);
TextView t = (TextView)findViewById(R.id.poolName);
TextView t2 = (TextView)findViewById(R.id.khashMe);
TextView t3 = (TextView)findViewById(R.id.khashPool);
TextView t4 = (TextView)findViewById(R.id.khashNet);
t.setText(data.getName());
t2.setText(data.getMyHash());
t3.setText(data.getPoolHash());
t4.setText(data.getNetHash());
return "Hello World. If you see this, you probably hack. Get out.";
}
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
}
}
Here's the class MPOSDashStruct:
package io.kd.figgycity50.mpos.mposchecker;
import com.google.gson.annotations.SerializedName;
/**
* Created by George on 25/05/2014.
*/
public class MPOSDashStruct {
public static class getdashboarddata {
public static class data {
public static class personal {
public static int hashrate;
}
public static class pool {
public static int hashrate;
public static int difficulty;
public static class info {
#SerializedName("name")
public static String poolName;
public static String currency;
}
}
public static class network {
public static int hashrate;
public static int difficulty;
}
}
}
public String getName() {
return getdashboarddata.data.pool.info.poolName;
}
public String getCurrency() {
return getdashboarddata.data.pool.info.currency;
}
public int getPoolHash() {
return getdashboarddata.data.pool.hashrate;
}
public int getPoolDiff() {
return getdashboarddata.data.pool.difficulty;
}
public int getMyHash() {
return getdashboarddata.data.personal.hashrate;
}
public int getNetHash() {
return getdashboarddata.data.network.hashrate;
}
}
The code is seemingly good, and Android Studio has no errors.
EDIT 2: contentAsString ouputs
05-25 17:30:12.976 29974-29988/io.kd.figgycity50.mpos.mposchecker D/INFO﹕ {"getdashboarddata":{"version":"1.0.0","runtime":632.7919960022,"data":{"raw":{"personal":{"hashrate":0},"pool":{"hashrate":1675289},"network":{"hashrate":38541151.201,"esttimeperblock":61.161346587453,"nextdifficulty":538.41366248,"blocksuntildiffchange":1}},"personal":{"hashrate":0,"sharerate":"0.0000","sharedifficulty":0,"shares":{"valid":0,"invalid":0,"invalid_percent":0,"unpaid":0},"estimates":{"block":0,"fee":0,"donation":0,"payout":0}},"pool":{"info":{"name":"RAPIDHASH","currency":"DOGE"}
using Log.d("INFO", contentAsString)
EDIT: After using getContentLength, the new logcat is this:
05-25 17:50:19.203 5143-5157/io.kd.figgycity50.mpos.mposchecker W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x41bd4ba8)
05-25 17:50:19.203 5143-5157/io.kd.figgycity50.mpos.mposchecker E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: io.kd.figgycity50.mpos.mposchecker, PID: 5143
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.NegativeArraySizeException: -1
at io.kd.figgycity50.mpos.mposchecker.MainActivity$DownloadWebpageTask.readIt(MainActivity.java:120)
at io.kd.figgycity50.mpos.mposchecker.MainActivity$DownloadWebpageTask.downloadUrl(MainActivity.java:104)
at io.kd.figgycity50.mpos.mposchecker.MainActivity$DownloadWebpageTask.doInBackground(MainActivity.java:71)
at io.kd.figgycity50.mpos.mposchecker.MainActivity$DownloadWebpageTask.doInBackground(MainActivity.java:64)
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)
which points to this line of my code:
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len]; //this line, others added so you can understand
reader.read(buffer);
return new String(buffer);
}
EDIT 3: Directing Gson to handle the Reader worked well, but new errors arise again. Logcat:
05-26 09:17:52.459 11810-11810/io.kd.figgycity50.mpos.mposchecker E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: io.kd.figgycity50.mpos.mposchecker, PID: 11810
java.lang.RuntimeException: Unable to start activity ComponentInfo{io.kd.figgycity50.mpos.mposchecker/io.kd.figgycity50.mpos.mposchecker.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
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: java.lang.NullPointerException
at io.kd.figgycity50.mpos.mposchecker.MainActivity.onCreate(MainActivity.java:49)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
            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)
which points to:
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String prefPool = sharedPref.getString("pref_pool", "https://doge.rapidhash.net/");
String prefKey = sharedPref.getString("pref_key", "XXXX");
new DownloadWebpageTask().execute(prefPool + "index.php?page=api&action=getdashboarddata&api_key=" + prefKey);
TextView t = (TextView)findViewById(R.id.poolName); // this line
TextView t2 = (TextView)findViewById(R.id.khashMe);
TextView t3 = (TextView)findViewById(R.id.khashPool);
TextView t4 = (TextView)findViewById(R.id.khashNet);
t.setText(dashStruct.getName());
t2.setText(dashStruct.getMyHash());
t3.setText(dashStruct.getPoolHash());
t4.setText(dashStruct.getNetHash());
}
I don't know why you do this
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
If your JSON is longer than that, you're breaking it into pieces that are not parseable by JSON parsers. Read the full JSON string.
Get the content length from the response.
int len = conn.getContentLength();
From Edit 3 above, the following line seems to be throwing the NullPointerException:
t.setText(dashStruct.getName());
I can tell that you declare dashStruct as a class level variable which is getting initialized in the AsyncTask DownloadWebpageTask.
By design, an AsyncTask will be executed off the main thread (to be precise, the AsyncTask#doInBackground(T) method). If DownloadWebpageTask hasn't finished initializing dashStruct when the main thread executes t.setText(dashStruct.getName()); - an NPE will be thrown - dashStruct is null.
To get past this exception, override onPostExecute() in DownloadWebpageTask and move the following code to it (remove it from onCreate(Bundle)):
#Override
protected void onPostExecute(String result) {
if (dashStruct != null) {
t.setText(dashStruct.getName());
t2.setText(dashStruct.getMyHash());
t3.setText(dashStruct.getPoolHash());
t4.setText(dashStruct.getNetHash());
} else {
// Deal with dashStruct being null
}
}
I notice that in your original posting, you are updating your UI (setting textview text) from the DownloadWebpageTask#doInBackground(String...). This will throw an IllegalStateException as doInBackground() is processed off the main thread - the only thread allowed to touch your UI. onPostExecute() is processed on the main thread. And that's where your UI logic should go.

Categories

Resources