So I have a code like this, the reason I write it to a class is because sometime HTTP response can delay or contain error. runOnUiThread required activity
public class RemoteUtilities
{
public static RemoteUtilities remoteUtilities = null;
private Activity uiActivity;
public RemoteUtilities(Activity uiActivity)
{
this.uiActivity = uiActivity;
}
public static RemoteUtilities getInstance(Activity uiActivity)
{
if (remoteUtilities == null)
{
remoteUtilities = new RemoteUtilities(uiActivity);
}
remoteUtilities.setUiActivity(uiActivity);
return remoteUtilities;
}
public void setUiActivity(Activity uiActivity)
{
this.uiActivity = uiActivity;
}
public HttpURLConnection openConnection(String urlString)
{
HttpURLConnection conn = null;
try
{
URL url = new URL(urlString);
conn = (HttpURLConnection) url.openConnection();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
if (conn == null)
{
uiActivity.runOnUiThread(new Runnable()
{
@Override
public void run()
{
Toast.makeText(uiActivity, "Check Internet", Toast.LENGTH_LONG).show();
}
});
}
return conn;
}
public boolean isConnectionOkay(HttpURLConnection conn)
{
try
{
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK)
{
return true;
}
}
catch (IOException e)
{
e.printStackTrace();
uiActivity.runOnUiThread(new Runnable()
{
@Override
public void run()
{
Toast.makeText(uiActivity, "Problem with API Endpoint", Toast.LENGTH_LONG).show();
}
});
}
return false;
}
public String getResponseString(HttpURLConnection conn)
{
String data = null;
try
{
InputStream inputStream = conn.getInputStream();
byte[] byteData = IOUtils.toByteArray(inputStream);
data = new String(byteData, StandardCharsets.UTF_8);
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
conn.disconnect();
}
return data;
}
}
I will probably use this class for a few times.
As you can see I do this because I need it to run on thread and making a toast.
The IDE warn I have memory leak but I'm not sure about it.
Is this fine? Or is there a more elegant way to write this class?
When the end of stream has been reached, you have to close the InputStream.
finally {
inputStream?.close()
}
or try-with-resources construct:
try(InputStream inputstream = conn.getInputStream()) {}
Also you cannot hold activity as parameter. It will save context when activity is destroyed. Remove that part
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.