I'm using this codes in asynctask for load data from URL. I added internet permissions in manifest.xml, I haven't any errors on Android Studio but when i debugging application, going crash. Where is my fault?
protected Void doInBackground(Void... params) {
try {
URL url = new URL("my_url");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
jsonString = buffer.toString();
if(connection != null) { connection.disconnect(); }
try {
if(reader != null) { reader.close(); }
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
Thanks..
Related
I have implemented AsyncTask in Activity properly (based on many sources).
Also I have investigated SocketTimeoutException and catche exception as you can see in the code below.
Anyway when I stop webapi and simulate SocketTimeoutException the app crashes immediately. (Please, check the error's message.)
Debuging code goes to IOException and then I see the error's message and app restarts.
Code
private class FetchHauls extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
AppSettings.ComplexPreferences complexPreferences = AppSettings.ComplexPreferences.getComplexPreferences(context, "App_Settings", 0);
AppSettings appSettings = complexPreferences.getObject("App_Settings", AppSettings.class);
if (appSettings != null) {
String uri = appSettings.getIpAddress() + "/api/Version1/GetGrandTotalStats";
GrandTotalStatsRequest grandTotalStatsRequest = new GrandTotalStatsRequest();
Date d = new Date();
CharSequence timeOfRequest = DateFormat.format("yyyy-MM-dd HH:mm:ss", d.getTime());
grandTotalStatsRequest.AtTime = timeOfRequest.toString();
grandTotalStatsRequest.DeviceID = appSettings.getDeviceID();
grandTotalStatsRequest.DeviceSerialNumber = appSettings.getSerialNumber();
Gson gson = new Gson();
String json = gson.toJson(grandTotalStatsRequest);
//Connect
urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(60000);
urlConnection.setReadTimeout(55000);
urlConnection.connect();
//Write
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(json);
writer.close();
outputStream.close();
String result = null;
//Read
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String l = null;
StringBuilder sb = new StringBuilder();
while ((l = bufferedReader.readLine()) != null) {
sb.append(l);
}
bufferedReader.close();
result = sb.toString();
}
return result;
}
} catch (IOException e) {
} catch (Exception e) {
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException ex) {
}
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (isCancelled()) {
return;
}
swiperefresh.setRefreshing(false);
taskFetchHauls = null;
if (TextUtils.isEmpty(s)) return;
try {
// Some code...
} catch (Exception ex) {
Log.e(PAGE_TITLE, ex.getMessage());
}
}
}
}
Error
java.net.SocketTimeoutException: failed to connect to /172.15.15.2 (port 1067) after 60000ms
at libcore.io.IoBridge.connectErrno(IoBridge.java:169)
at libcore.io.IoBridge.connect(IoBridge.java:122)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:452)
at java.net.Socket.connect(Socket.java:884)
at com.android.okhttp.internal.Platform.connectSocket(Platform.java:117)
at com.android.okhttp.internal.http.SocketConnector.connectRawSocket(SocketConnector.java:160)
at com.android.okhttp.internal.http.SocketConnector.connectCleartext(SocketConnector.java:67)
at com.android.okhttp.Connection.connect(Connection.java:152)
at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:185)
at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:128)
at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:341)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:433)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
at android.apps.ktk.company.gpsmegatracker.Activities.GrandStatActivity$FetchHauls.doInBackground(GrandStatActivity.java:291)
at android.apps.ktk.company.gpsmegatracker.Activities.GrandStatActivity$FetchHauls.doInBackground(GrandStatActivity.java:259)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Disconnected from the target VM, address: 'localhost:8617', transport: 'socket'
If you want to catch a SocketTimeoutException, then you should use the following pattern. Note carefully that we catch exceptions from most specific to most general. Because SocketTimeoutException is a child of IOException, we catch the former first. Using the reverse order will result in the error you were seeing. Finally, we catch general Exception last.
#Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
// make the async call
}
catch (SocketTimeoutException se) {
// display timeout alert to user
}
catch (IOException e) {
// handle general IO error
}
catch (Exception e) {
// just in case you missed anything else
}
finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException ex) {
}
}
}
}
in my application i am using below code that returns input stream
QBContent.downloadFileById(fileId, new QBEntityCallback<InputStream>() {
#Override
public void onSuccess(final InputStream inputStream, Bundle params) {
long length = params.getLong(Consts.CONTENT_LENGTH_TAG);
Log.i(TAG, "content.length: " + length);
// use inputStream to download a file
}
#Override
public void onError(QBResponseException errors) {
}
}, new QBProgressCallback() {
#Override
public void onProgressUpdate(int progress) {
}
});
now i want to covert input steam into file then want to do two things with that file
1. how can i save it to user's phone storage
2. save it temporarily and display's it in pdf viewer using intent
note: returned file will be in pdf formal
You did not mentionned if you wanted to store in external or internal storage, I wrote this example for internal storage
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line).append('\n');
}
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("file.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(total.toString());
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
Don't forget to use try/catch and close what needs to be closed
You can use below code to store InputStream in File.
But you need to pass file path and where you want to store file in storage.
InputStream inputStream = null;
BufferedReader br = null;
try {
// read this file into InputStream
inputStream = new FileInputStream("/Users/mkyong/Downloads/file.js");
br = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
System.out.println(sb.toString());
System.out.println("\nDone!");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In here the code with BufferedReaderand line = reader.readLine() works
public class WeatherService extends AsyncTask<TaskParams, Void, String> {
private WeatherServiceCallback callback;
private Exception exception;
public WeatherService(WeatherServiceCallback callback) {
this.callback = callback;
}
#Override
protected String doInBackground(TaskParams... params) {
try {
URL url = new URL("http://api.openweathermap.org/data/2.5/weather?lat=" +
params[0].getLat() + "&lon=" + params[0].getLon() +
"&units=" + TaskParams.getUnits() +
"&type=" + TaskParams.getAccuracy() + "&lang=" + TaskParams.getLanguage() +
"&appid=10660a09a9fb335d72f576f7aa1bbe5b");
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
} catch (MalformedURLException e) {
exception = e;
} catch (IOException e) {
exception = e;
}
return null;
}
#Override
protected void onPostExecute(String s)
{
if (s == null && exception != null)
{
callback.serviceFailure(exception);
return;
}
try
{
JSONObject data = new JSONObject(s);
Parameters parameters = new Parameters();
parameters.poopulate(data);
callback.serviceSuccess(parameters);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I copy-pasted code to other class since it has very similar functionality and now for no reason I'm getting NullPointerException in while ((line = reader.readLine()) != null) and I have no idea why since as I said it's copy-pasted (I only changed URL and object returned if serivce succeeds)
public class PollutionService extends AsyncTask<TaskParams, Void, String>
{
private PollutionServiceCallback callback;
private Exception exception;
private URLConnection connection;
private InputStream inputStream;
private InputStreamReader streamReader;
private BufferedReader reader;
public PollutionService(PollutionServiceCallback callback) {
this.callback = callback;
}
#Override
protected String doInBackground(TaskParams... params) {
try
{
URL url = new URL("http://api.openweathermap.org/pollution/v1/co/" + params[0].getLat() +
"," + params[0].getLon() + "/current.json?&appid=10660a09a9fb335d72f576f7aa1bbe5b");
try
{
connection = url.openConnection();
}
catch (IOException e)
{
exception = new Exception("Connection error");
}
try
{
inputStream = connection.getInputStream();
}
catch (IOException e)
{
exception = new Exception("Input stream error");
}
try
{
streamReader = new InputStreamReader(inputStream);
}
catch (NullPointerException e)
{
exception = new Exception("Input stream reader error");
}
try
{
reader = new BufferedReader(streamReader);
}
catch (NullPointerException e)
{
exception = new Exception("Buffered reader error");
}
StringBuilder builder = new StringBuilder();
String line;
try
{
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
}
catch (IOException e)
{
exception = e;
}
return builder.toString();
}
catch (MalformedURLException e)
{
exception = e;
}
return null;
}
#Override
protected void onPostExecute(String s)
{
if (s == null && exception != null)
{
callback.pollutionServiceFailure(exception);
return;
}
try
{
JSONObject data = new JSONObject(s);
PollutionParameters parameters = new PollutionParameters();
parameters.poopulate(data);
callback.pollutionServiceSuccess(parameters);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Any clue?
EDIT
This is rewritten code for PollutionActivity. Callback function serviceFailure prints now the URL address on my phone's screen
public class PollutionService extends AsyncTask<TaskParams, Void, String>
{
private PollutionServiceCallback callback;
private Exception exception;
public PollutionService(PollutionServiceCallback callback) {
this.callback = callback;
}
#Override
protected String doInBackground(TaskParams... params) {
try
{
URL url = new URL("http://api.openweathermap.org/pollution/v1/co/" + params[0].getLat() +
"," + params[0].getLon() + "/current.json?&appid=10660a09a9fb335d72f576f7aa1bbe5b");
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
InputStreamReader streamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder builder = new StringBuilder();
String line;
try
{
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
}
catch (IOException e)
{
exception = e;
}
return builder.toString();
}
catch (MalformedURLException e)
{
exception = e;
}
catch (IOException e)
{
exception = e;
}
return null;
}
#Override
protected void onPostExecute(String s)
{
if (s == null && exception != null)
{
callback.pollutionServiceFailure(exception);
return;
}
try
{
JSONObject data = new JSONObject(s);
PollutionParameters parameters = new PollutionParameters();
parameters.poopulate(data);
callback.pollutionServiceSuccess(parameters);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Debugging showed me that code jumps to exception after
InputStream inputStream = connection.getInputStream();
If you are getting NPE for reader then it means that reader is not getting initialized and going null.Your code is getting crash at line 23 and 89. So I believe that the problem is right at the start somewhere and not at the point itself, may be some object is going null like connection.Since line number is not displayed here.Check null pointer for every object like if (connection!=null). Since the initial data is coming null,maybe input stream or some other data,hence your reader object is not getting initialized.Also check if you are getting value for every object in debug.
when the connection is so low i get an exception " failed to connect to : http ......", this is my code, can any one please helps me to avoid the exception.
when the connection is so low i get an exception " failed to connect to : http ......", this is my code, can any one please helps me to avoid the exception
private void parseM3uUrlAndPrepare_new(final String url) {
AsyncTask<String, Integer, String> asyn = new AsyncTask<String, Integer, String>(){
URL the_url;
HttpURLConnection conn;
String filePath = "";
InputStream inputStream;
HttpGet getRequest;
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
the_url = new URL(url);
conn = (HttpURLConnection) the_url.openConnection(Proxy.NO_PROXY);
getRequest = new HttpGet(url);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(String... params) {
if(conn != null) {
try {
inputStream = new BufferedInputStream(conn.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null) {
if (line.startsWith("#")) {
}
else if (line.length() > 0) {
filePath = "";
if (line.startsWith("http://")) { // Assume it's a full URL
filePath = line;
}
else { // Assume it's relative
try{
filePath = getRequest.getURI().resolve(line).toString();
}
catch(IllegalArgumentException e){
e.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
try {
inputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
return filePath;
}
#Override
protected void onPostExecute(String filePath) {
try {
mediaPlayer.setDataSource(filePath);
DATA_SET = true;
mediaPlayer.prepareAsync(); //this will prepare file a.k.a buffering
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (IllegalStateException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
};
asyn.execute("");
}
Maybe the problem is the BufferedInputStream. I wrote this code (a long time ago) if you want to try it.
Give an input stream to the fonction and let it work.
import java.io.InputStream;
import java.util.Scanner;
/**
* Created by badetitou.
*/
public class ReadIt {
public static String ReadIt(InputStream is){
return new Scanner(is,"UTF-8").useDelimiter("").next();
}
}
I am trying to make the computer read a text file full of words and add it to an ArrayList. I made it work on a regular Java application, but can't get it to work on Android. Can someone help me out?
try {
FileInputStream textfl = (FileInputStream) getAssets().open("test.txt");
DataInputStream is = new DataInputStream(textfl);
BufferedReader r = new BufferedReader(new InputStreamReader(is));
String strLine;
while ((strLine = r.readLine()) != null) {
tots.add(strLine); //tots is the array list
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I keep getting a error. The text file is 587kb, so could that be a problem?
try this.
private static String readTextFile(String fileName)
{
BufferedReader in = null;
try
{
in = new BufferedReader(new InputStreamReader(getAssets().open(fileName)));
String line;
final StringBuilder buffer = new StringBuilder();
while ((line = in.readLine()) != null)
{
buffer.append(line).append(System.getProperty("line.separator"));
}
return buffer.toString();
}
catch (final IOException e)
{
return "";
}
finally
{
try
{
in.close();
}
catch (IOException e)
{
// ignore //
}
}
}