Check if URL exists or not on Server - android

This is my code which I am using to verify, URL exists or not on Server, but always getting not exist however link is alive
Where I am doing mistake in my code, why I am always getting "doesnot exist !"
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String customURL = "http://www.desicomments.com/dc3/08/273858/273858.jpg";
boolean bResponse = exists(customURL);
if (bResponse==true)
{
Toast.makeText(MainActivity.this, "File exists!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "File does not exist!", Toast.LENGTH_SHORT).show();
}
}
public static boolean exists(String URLName){
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
}

You will get Network On Main Thread Exception
Look at NetworkOnMainThreadException
so your method always returns false because of:
catch (Exception e) {
e.printStackTrace();
return false;
}
quick fix:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String customURL = "http://www.desicomments.com/dc3/08/273858/273858.jpg";
MyTask task = new MyTask();
task.execute(customURL);
}
private class MyTask extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPreExecute() {
}
#Override
protected Boolean doInBackground(String... params) {
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(params[0]).openConnection();
con.setRequestMethod("HEAD");
System.out.println(con.getResponseCode());
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
#Override
protected void onPostExecute(Boolean result) {
boolean bResponse = result;
if (bResponse==true)
{
Toast.makeText(MainActivity.this, "File exists!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "File does not exist!", Toast.LENGTH_SHORT).show();
}
}
}
}
With a ScheduledThreadPoolExecutor:
but remember to shut down it!!
public class MainActivity extends Activity {
String customURL;
String msg = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customURL = "http://www.desicomments.com/dc3/08/273858/273858.jpg";
final ScheduledThreadPoolExecutor myTimer = new ScheduledThreadPoolExecutor(1);
myTimer.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(customURL).openConnection();
con.setRequestMethod("HEAD");
System.out.println(con.getResponseCode());
if(con.getResponseCode() == HttpURLConnection.HTTP_OK){
msg = "File exist!";
}else{
msg = "File does not exist!";
}
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
}
catch (Exception e) {
e.printStackTrace();
return;
}
}
}, 0,10000, TimeUnit.MILLISECONDS);
}

Change your exists() to this
public boolean exists(String url){
HttpURLConnection huc = ( HttpURLConnection ) url.openConnection ();
huc.setRequestMethod ("GET"); //OR huc.setRequestMethod ("HEAD");
huc.connect () ;
int code = huc.getResponseCode() ;
System.out.println(code);
if(code==200)
return true;
else
return false;
}

Use if(bResponse) instead of if(bResponse==true)

you can use the follow code to try.
final String customURL = "http://www.desicomments.com/dc3/08/273858/273858.jpg";
new Thread(){
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
try {
URL url = new URL(customURL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("HEAD");
con.connect();
Log.i(TAG, "con.getResponseCode() IS : " + con.getResponseCode());
if(con.getResponseCode() == HttpURLConnection.HTTP_OK){
Log.i(TAG, "Sucess");
}
} catch (Exception e) {
e.printStackTrace();
Log.i(TAG, "fail");
}
}
}.start();
Reason: After android 2.3, you can't perform a networking operation on its main thread,
if you do so, there will be can exception and you can't get the right result.
So if you want the application to perform a networking operation, you can use another Thread to do it.

I use this code to verify url alive. I have tested this code with image url
Example:
url = "https://ima.vn/wp-content/uploads/2017/11/ima-sofa-titan-trungkinh-1-of-3.jpg"
message = "Image url";
public void assertUrlalive(String url, String message) {
try {
URL myUrl = new URL(url);
HttpURLConnection huc = (HttpURLConnection) myUrl.openConnection();
assertEquals(huc.getResponseCode(), 200, message);
} catch (IOException e) {
e.printStackTrace();
logger.error("Connection Err: " + e.getMessage());
}
}

Related

My UI is not updating after API call of openweather

I want to parse JSON from the Openweather API but after many iterations and debugging, my JSON string is not updating, I do not think that there is any problem still the temperatures( minTemperature and maxTemperature) and the name of the place(mPlace) is not set, also I logged the maxtemperature but the console is showing nothing please look into my code.
public class MainActivity extends AppCompatActivity {
private EditText placeText;
private Button enterPlaceButton;
private TextView minTemperature;
private TextView maxTemperature;
private TextView mPlace;
private static final String AppID ="56a5e01eba3af36a7a9b7b210a437d09";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("Weather");
placeText = findViewById(R.id.myPlaceEditText);
enterPlaceButton = findViewById(R.id.enterPlace);
minTemperature = findViewById(R.id.minTemperature);
maxTemperature = findViewById(R.id.maxTemperature);
mPlace = findViewById(R.id.mPlace);
}
#Override
protected void onResume() {
final URL[] url = {null};
enterPlaceButton.setOnClickListener(v -> {
url[0] = makeUrl(placeText.getText().toString());
placeText.setText("");
});
if (url[0] != null) {
MyAsync myAsync = new MyAsync();
myAsync.execute(url[0]);
}
super.onResume();
}
public URL makeUrl(String place) {
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.scheme("http");
uriBuilder.authority("api.openweathermap.org/");
uriBuilder.appendPath("data");
uriBuilder.appendPath("2.5");
uriBuilder.appendPath("weather");
uriBuilder.appendQueryParameter("q",place);
uriBuilder.appendQueryParameter("appid",AppID);
try {
return new URL(uriBuilder.build().toString());
} catch (MalformedURLException e) {
Toast.makeText(MainActivity.this, "Sorry could not able to fetch the Data", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
return null;
}
public class MyAsync extends AsyncTask<URL, Void, String> {
#Override
protected String doInBackground(URL... urls) {
StringBuilder jsonResponseBuilder = new StringBuilder();
try {
HttpURLConnection httpURLConnection = (HttpURLConnection) urls[0].openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == 200) {
InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = bufferedReader.readLine();
while (line != null) {
jsonResponseBuilder.append(line);
line = bufferedReader.readLine();
}
httpURLConnection.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Sorry could not able to fetch the Data", Toast.LENGTH_SHORT).show();
}
Log.d(MyAsync.class.getName(),jsonResponseBuilder.toString());
return jsonResponseBuilder.toString();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
setDataFromJSON(s);
super.onPostExecute(s);
}
public void setDataFromJSON(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONObject getMainObject = jsonObject.getJSONObject("main");
String maxTemp = getMainObject.getString("temp_max");
Log.i(MainActivity.class.getName(), maxTemp);
maxTemperature.setText(maxTemp);
String minTemp = getMainObject.getString("temp_min");
minTemperature.setText(minTemp);
mPlace.setText(jsonObject.getString("name"));
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Sorry could not able to fetch the Data", Toast.LENGTH_SHORT).show();
}
}
}
}

I am creating change password functionality in my android application which crashing on getResponsecode()

I have provided onCreate() and New password method where on debugging, it is crashing on getResponsecode(). It is crashing and not getting response. It is not going to get response from server.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.change_password_activity);
list(getIntent().getExtras().getString("JSON_Object"));
CurrentPwdCheck();
NewpwdCheck();
btnSubmit= (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
NewPwd();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
public void NewPwd() throws IOException, JSONException {
String myPwd=new_pwd.getText().toString();
String Surl="http://inmeets.com/ChangePwd.php?uid="+uid+"&NewPwd="+myPwd;
URL url = null;
HttpURLConnection conn = null;
url = new URL(Surl);
conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(1000);
if( conn.getResponseCode()==203) {
Toast.makeText(getBaseContext(), "your password changed", Toast.LENGTH_SHORT).show();
}
}
You can not perform network actions from main thread because it will slow down the UI. Create a new AsyncTask to interact with your server.
You can also use thread instead of AsyncTask. But AsyncTask would be preferably good because it is intelligent than thread in thread you have to manage all thing like run network call on background and update the UI in main thread.
If you really want some different than AsyncTask bellow is the thread concept
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.change_password_activity);
list(getIntent().getExtras().getString("JSON_Object"));
CurrentPwdCheck();
NewpwdCheck();
btnSubmit= (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
NewPasword pwd = new NewPasword();
pwd.start();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
class NewPasword extends Thread{
#Override
public void run() {
String myPwd=new_pwd.getText().toString();
String Surl="http://inmeets.com/ChangePwd.php?uid="+uid+"&NewPwd="+myPwd;
URL url = null;
HttpURLConnection conn = null;
url = new URL(Surl);
conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(1000);
if( conn.getResponseCode()==203) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getBaseContext(), "your password
changed", Toast.LENGTH_SHORT).show();
}
});
}
}
}

Can I search devices and computers in the same wifi network?

I'm trying to search for devices and equipment which are connected to the same wifi network to which my device is connected. I using the following code but until now I haven't had any success
new AsyncTask<Void, Void, Boolean>() {
URL[] urls;
URL proveUrl;
HttpURLConnection con;
private boolean next(int position){
if (position++ < urls.length){
try {
proveUrl = new URL(urls[position].getHost() + ":36000");
} catch (MalformedURLException e) {
Toast.makeText(SDCardImagesActivity.this, "Malformed URL", Toast.LENGTH_SHORT).show();
}
return true;
}else{
return false;
}
}
#Override
protected void onPreExecute() {
wifiManager.getScanResults().toArray(urls);
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Void... params) {
try {
proveUrl =new URL(urls[0].getHost() + ":36000");
} catch (MalformedURLException e) {
Toast.makeText(SDCardImagesActivity.this, "Malformed URL", Toast.LENGTH_SHORT).show();
}
return prove();
}
#Override
protected void onProgressUpdate(Void... values) {
direccionIp = proveUrl.getHost();
super.onProgressUpdate(values);
}
private Boolean prove(){
int position = 0;
try {
con = (HttpURLConnection) proveUrl.openConnection();
BufferedInputStream req = new BufferedInputStream(con.getInputStream());
} catch (IOException e) {
if (next(position)){
position++;
prove();
}else{
return false;
}
}
return true;
}
};
Somebody knows how to do this? Thanks

How to use multiple AsyncTasks

I'm coding the client side of an Android application which uses sockets. Since I'm new with AsyncTask, I coded something simple to test my understanding. Here is what I have, it seems to be correct:
public class Messaggi extends ActionBarActivity implements OnClickListener {
LinearLayout mLayout;
ScrollView scroll;
EditText writeMessage;
Button send;
Socket connection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_messaggi);
mLayout = (LinearLayout) findViewById(R.id.linearVertical);
scroll = (ScrollView) findViewById(R.id.scrollView1);
writeMessage= (EditText)findViewById(R.id.ScriviMessaggio);
send= (Button)findViewById(R.id.invia);
send.setOnClickListener(this);
LavoraDietro asd = new LavoraDietro();
asd.execute();
}
#Override
public void onClick(View v) {
}
private void updateScroll(){
scroll.post(new Runnable() {
#Override
public void run() {
scroll.fullScroll(View.FOCUS_DOWN);
}
});
}
private TextView createNewTextView(String text) {
final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(this);
textView.setLayoutParams(lparams);
textView.setText("Client: " + text);
return textView;
}
private class LavoraDietro extends AsyncTask<Void, Void, Boolean> {
String mex;
#Override
protected Boolean doInBackground(Void... params){
try {
InetAddress local = InetAddress.getByName("192.168.1.79");
Socket connection= new Socket(local , 7100);
DataOutputStream output = new DataOutputStream(connection.getOutputStream());
output.writeUTF("Client: Server prova");
output.flush();
DataInputStream input = new DataInputStream(connection.getInputStream());
mex= input.readUTF();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}catch(Exception e){
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if(result == true){
mLayout.addView(createNewTextView("Sono connesso al server"));
mLayout.addView(createNewTextView("I canali sono aperi.."));
mLayout.addView(createNewTextView(mex));
updateScroll();
}
else{
mLayout.addView(createNewTextView("ERRORE CONNESSIONE AL SERVER "));
updateScroll();
}
}
}
}
When the connection to the server is established, the client sends a test meesage and the server should send the same message to the client, where it is printed.
But my task is to establish the connection immediatly when the app is opened and send a message only when the button "send" is pressed. Is possible to create multiple AsyncTasks and make them work at the same time without crashing the application? If yes, can you please post an example of how can I do this?
EDITED CODE
This is my new code:
public class Messaggi extends ActionBarActivity implements OnClickListener {
LinearLayout mLayout;
ScrollView scroll;
EditText writeMessage;
Button send;
Socket connection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_messaggi);
mLayout = (LinearLayout) findViewById(R.id.linearVertical);
scroll = (ScrollView) findViewById(R.id.scrollView1);
writeMessage= (EditText)findViewById(R.id.ScriviMessaggio);
send= (Button)findViewById(R.id.invia);
send.setOnClickListener(this);
LavoraDietro asd = new LavoraDietro();
asd.execute();
}
#Override
public void onClick(View v) {
CliccaInvia asd123 = new CliccaInvia();
asd123.execute(connection);
}
private void updateScroll(){
scroll.post(new Runnable() {
#Override
public void run() {
scroll.fullScroll(View.FOCUS_DOWN);
}
});
}
private TextView createNewTextView(String text) {
final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(this);
textView.setLayoutParams(lparams);
textView.setText("Client: " + text);
return textView;
}
private class LavoraDietro extends AsyncTask<Void, Void, Socket> {
String mex;
#Override
protected Socket doInBackground(Void... params){
try {
InetAddress local = InetAddress.getByName("192.168.1.79");
connection= new Socket(local , 7100);
DataInputStream input = new DataInputStream(connection.getInputStream());
mex = input.readUTF();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
return connection;
}
#Override
protected void onPostExecute(Socket result) {
super.onPostExecute(result);
if(result != null){
mLayout.addView(createNewTextView("Sono connesso al server"));
mLayout.addView(createNewTextView("I canali sono aperi.."));
mLayout.addView(createNewTextView(mex));
updateScroll();
}
else{
mLayout.addView(createNewTextView("ERRORE CONNESSIONE AL SERVER "));
updateScroll();
}
}
}
private class CliccaInvia extends AsyncTask<Socket, Void, Boolean>{
#Override
protected Boolean doInBackground(Socket... params) {
try {
DataOutputStream output = new DataOutputStream(connection.getOutputStream());
output.writeUTF("Client: Server prova");
output.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if(result == true){
mLayout.addView(createNewTextView("Message Sent"));
aggiornaScroll();
}
else{
mLayout.addView(createNewTextView("Error sending Mex "));
aggiornaScroll();
}
}
}
But this doesn't work.. :(
Well if you need to spawn a lot of tasks and keep track of them all you could do something like this
List<LavoraDietro> tasks = new ArrayList<LavoraDietro>();
LavoraDietro task = new LavoraDietro();
task.execute;
tasks.add(task);
then in your LavoraDietro in the onPostExecute
tasks.remove(this);
But there is a million different ways you could make connections if you want. I recommend Apache's library. http://hc.apache.org/httpclient-3.x/
Here is an example of how you might make a connection, just call this function from inside the background of your task.
public static InputStream getHTTPRequest(String url, ArrayList<NameValuePair> parameters, ArrayList<NameValuePair> headers)
{
final String TAG = "getHTTPRequest";
HttpGet getRequest = new HttpGet(url);
// attach all and any params
if (parameters != null && parameters.size() > 0)
{
HttpParams params = getRequest.getParams();
for (NameValuePair param : parameters)
{
params.setParameter(param.getName(), param.getValue());
}
getRequest.setParams(params);
}
// attach all and any headers
if (headers != null && headers.size() > 0)
{
for (NameValuePair header : headers)
{
getRequest.addHeader(header.getName(), header.getValue());
}
}
getRequest.addHeader("Content-type", "application/json");
getRequest.addHeader("Accept", "application/json");
DefaultHttpClient client = new DefaultHttpClient();
try
{
HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK)
{
Log.d(TAG, "status not ok");
Log.d(TAG, "status = " + Integer.toString(statusCode));
Log.d(TAG, "url = " + getRequest.getURI().toString());
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
Log.d(TAG, "returning valid content");
return getResponseEntity.getContent();
} catch (IOException e)
{
Log.d(TAG, "IOException: getRequest.abort");
getRequest.abort();
}
return null;
}

PDF is not getting download form url

I am very new with android and doing this first time. I am trying to download pdf form url in my app but its not getting downloaded. I really got messed up with this. I don't what i am missing ,why this is not working for me. Please help me to do this.
Here i am pasting my code:
public class ProductBrochureActivity extends Activity {
private static String cookie;
private static String nid;
WebView webViewForBrochureAndVideo;
private String prodBrochureURL;
private String prodVideoURL;
private static int clickedItemId;
ActionBar actionBar;
private static HashMap<String, String> cookieWithRequest = new HashMap<String, String>();
static Object json;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product_brochure);
actionBar = getActionBar();
actionBar.hide();
Intent intent = getIntent();
cookie = intent.getStringExtra(BsharpConstant.WEB_SERVICES_COOKIES);
nid = intent.getStringExtra(BsharpConstant.PRODUCT_NODE_ID);
clickedItemId = intent.getIntExtra(BsharpConstant.CLICKED_ITEM_ID, 0);
String jsonResponseFromWebservices = WebserviceBsharpUtil
.callWebServicesToGetTheProductBrochureAndVideo(cookie, nid);
urlFromResponse(jsonResponseFromWebservices);
cookieWithRequest.put(BsharpConstant.WEB_SERVICES_COOKIES, cookie);
switch (clickedItemId) {
case 0:
if (!prodBrochureURL.isEmpty()) {
try {
new DownloadFile();
} catch (ActivityNotFoundException e) {
Toast.makeText(this,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "No PDF is Attached with this Product",
Toast.LENGTH_SHORT).show();
}
break;
case 1:
if (!prodVideoURL.isEmpty()) {
try {
new DownloadFile();
} catch (ActivityNotFoundException e) {
Toast.makeText(this,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
break;
} else {
Toast.makeText(this, "No Video is Attached with this Product",
Toast.LENGTH_SHORT).show();
}
}
}
/**
* GetTheBrochureAndAttachedVideoURL
*
* #param jsonResponse
*/
public void urlFromResponse(String jsonResponse) {
try {
json = new JSONTokener(jsonResponse).nextValue();
if (json instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) json;
prodBrochureURL = jsonArray.getJSONObject(0).getString(
BsharpConstant.PRODUCT_BROCHURE_URL);
prodVideoURL = jsonArray.getJSONObject(0).getString(
BsharpConstant.PRODUCT_VIDEO_URL);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private class DownloadFile extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String filename = "brochure.pdf";
HttpURLConnection connection;
try {
URL url = new URL(prodBrochureURL);
connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty(
BsharpConstant.WEB_SERVICES_COOKIES, cookie);
connection.setDoOutput(true);
connection.connect();
} catch (IOException e1) {
return e1.getMessage();
}
File folderDir = new File(getExternalFilesDir("Bsharp_PDF")
+ "/Download");
File file = new File(folderDir, filename);
if (file.exists()) {
file.delete();
}
if ((folderDir.mkdirs() || folderDir.isDirectory())) {
try {
InputStream inputStream = connection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(
folderDir + "/" + filename);
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, len1);
}
fileOutputStream.close();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(),
"Unable to create folder", Toast.LENGTH_LONG).show();
}
return "Done";
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG)
.show();
super.onPostExecute(result);
}
}
}
In order for an AsyncTask (DownloadFile in your case) to be executed one has to explicitly call its execute(Params... params) method. In your case in addition to instantiating your task call execute without providing any parameters, i.e.
DownloadFile task = new DownloadFile();
task.execute();
Hope this helps.

Categories

Resources