I am trying to make a simple weather app. Everytime I try and access the Yahoo weather api to return a JSON object, I get this exception. To do the task without the api, I copy pasted the JSON object into a separate string and have been working with that string as the JSON object.
This is my asynch task:
public class WeatherInfoThread extends AsyncTask{
#Override
protected String doInBackground(Void... params) {
String resultString = null;
try {
url = new URL("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22"+location+"%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream = connection.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
try {
jsonInfo = bufferedReader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
resultString = jsonInfo;
try {
weatherinfo = new JSONObject(testString);
// Log.d(JSON_INFO,weatherinfo.toString()+"df");
JSONObject channel = weatherinfo.getJSONObject("query").getJSONObject("results").getJSONObject("channel");
JSONObject item = channel.getJSONObject("item");
currentTemp = item.getJSONObject("condition");
cCurrentInt = currentTemp.getInt("code");
forecast = item.getJSONArray("forecast");
cOne = forecast.getJSONObject(1).getString("text");
cTwo = forecast.getJSONObject(2).getString("text");
cThree = forecast.getJSONObject(3).getString("text");
cFour = forecast.getJSONObject(4).getString("text");
cFive = forecast.getJSONObject(5).getString("text");
dOne = forecast.getJSONObject(1).getString("day");
dTwo = forecast.getJSONObject(2).getString("day");
dThree = forecast.getJSONObject(3).getString("day");
dFour = forecast.getJSONObject(4).getString("day");
dFive = forecast.getJSONObject(5).getString("day");
// Log.d(JSON_INFO,forecast.get(1).toString()+"ddf");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
This is the error I got:
12-16 16:48:06.677 10523-10549/com.example.aakashmahesh.weatherapp E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at libcore.net.http.HttpConnection.(HttpConnection.java:70)
at libcore.net.http.HttpConnection.(HttpConnection.java:50)
at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:461)
at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433)
at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271)
at com.example.aakashmahesh.weatherapp.MainActivity$WeatherInfoThread.doInBackground(MainActivity.java:269)
at com.example.aakashmahesh.weatherapp.MainActivity$WeatherInfoThread.doInBackground(MainActivity.java:250)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
at libcore.io.Posix.getaddrinfo(Native Method)
at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:55)
at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at libcore.net.http.HttpConnection.(HttpConnection.java:70)
at libcore.net.http.HttpConnection.(HttpConnection.java:50)
at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:461)
at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433)
at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271)
at com.example.aakashmahesh.weatherapp.MainActivity$WeatherInfoThread.doInBackground(MainActivity.java:269)
at com.example.aakashmahesh.weatherapp.MainActivity$WeatherInfoThread.doInBackground(MainActivity.java:250)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: libcore.io.ErrnoException: getaddrinfo failed: EACCES (Permission denied)
at libcore.io.Posix.getaddrinfo(Native Method)
at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:55)
at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at libcore.net.http.HttpConnection.(HttpConnection.java:70)
at libcore.net.http.HttpConnection.(HttpConnection.java:50)
at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:461)
at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433)
at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271)
at com.example.aakashmahesh.weatherapp.MainActivity$WeatherInfoThread.doInBackground(MainActivity.java:269)
at com.example.aakashmahesh.weatherapp.MainActivity$WeatherInfoThread.doInBackground(MainActivity.java:250)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
12-16 16:48:06.677 1370-17136/system_process W/ActivityManager: Force finishing activity com.example.aakashmahesh.weatherapp/.MainActivity
12-16 16:48:06.737 1370-17136/system_process D/dalvikvm: GC_FOR_ALLOC freed 647K, 12% free 16559K/18695K, paused 10ms, total 10ms
12-16 16:48:06.767 10523-10523/com.example.aakashmahesh.weatherapp D/libEGL: loaded /system/lib/egl/libEGL_emulation.so
12-16 16:48:06.767 10523-10523/com.example.aakashmahesh.weatherapp D/libEGL: loaded /system/lib/egl/libGLESv1_CM_emulation.so
12-16 16:48:06.767 10523-10523/com.example.aakashmahesh.weatherapp D/libEGL: loaded /system/lib/egl/libGLESv2_emulation.so
[ 12-16 16:48:06.767 10523:10523 D/ ]
HostConnection::get() New Host Connection established 0xb8071030, tid 10523
read the error, will you?
Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?) at
May be you did not write the permission to access Internet in Manifest file
Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
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
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.
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);
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.