Using Android DownloadManager,how do i get file name? - android

I'm using DownloadManager class to manage downloads, i'm using this
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,subPath);
currently i'm setting subPath to some filename but how do i get filename from url?
I don't want to use cursor but some way to extract file name from uri.

You can use:
DownloadManager.COLUMN_TITLE
Please look at Android DownloadManager get filename
Hope this helps!

Well , if no cursor then try this:
class GetFileName extends AsyncTask<String, Integer, String>
{
protected String doInBackground(String... urls)
{
URL url;
String filename = null;
try {
url = new URL(urls[0]);
String cookie = CookieManager.getInstance().getCookie(urls[0]);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Cookie", cookie);
con.setRequestMethod("HEAD");
con.setInstanceFollowRedirects(false);
con.connect();
String content = con.getHeaderField("Content-Disposition");
String contentSplit[] = content.split("filename=");
filename = contentSplit[1].replace("filename=", "").replace("\"", "").trim();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
}
return filename;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
}
}

Related

ProgressBar disappears before the pdf load

I am using the com.github.barteksc:android-pdf-viewer:2.8.2 library for rendering the pdf from stream. For the small size pdf files the progress bar is working fine. Showing while loading and become invisible when loading completes. But when it loads large size pdf files. The ProgressBar runs for some time and disappear before the pdf appear on screen. How to make the ProgressBar to show until the pdf appear on screen. Also is there any ways to get the loading values for making the ProgressBar deterministic. My code is given below
class RetrievePDFStream extends AsyncTask<String,Void,InputStream>{
#Override
protected InputStream doInBackground(String... strings) {
InputStream inputStream = null;
try {
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
if (urlConnection.getResponseCode() == 200) {
inputStream = new BufferedInputStream((urlConnection.getInputStream()));
}
} catch (IOException e) {
return null;
}
return inputStream;
}
#Override
protected void onPostExecute(InputStream inputStream) {
pdfView.fromStream(inputStream).swipeHorizontal(false).load();
mProgress.setVisibility(View.GONE);
}
}
Basically your missing some listeners to help you with. Please check below code may help.
class RetrievePDFStream extends AsyncTask<String,Void,InputStream>implements OnLoadCompleteListener{
#Override
protected InputStream doInBackground(String... strings) {
InputStream inputStream = null;
try {
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
if (urlConnection.getResponseCode() == 200) {
inputStream = new BufferedInputStream((urlConnection.getInputStream()));
}
} catch (IOException e) {
return null;
}
return inputStream;
}
#Override
protected void onPostExecute(InputStream inputStream) {
pdfView.fromStream(inputStream).swipeHorizontal(false).onLoad(this).load();
// mProgress.setVisibility(View.GONE);
}
#Override
public void loadComplete(int nbPages) {
mProgress.setVisibility(View.GONE);
}
}

HttpURLConnection Cannot openConnection

#Override
protected Void doInBackground(String... params) {
String type = params[0];
String url= "http://10.0.2.2/login.php" ;
if(type.equals("Singin")) {
try {
URL Singin_url = new URL(url);
//Cannot not resolve method 'openConnection()'
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
return null;
}
Why won't it let me OpenConnection ??
and i cant go forward because it says 'connection' not initialized
You need to call the openConnection() method on the URL object Singin_url. You are calling it on a String object.
#Override
protected Void doInBackground(String... params)
{
String type = params[0];
String url= "http://10.0.2.2/login.php" ;
if(type.equals("Singin"))
{
try {
URL Singin_url = new URL(url);
HttpURLConnection connection = (HttpURLConnection)Singin_url.openConnection();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
return null;
}
Also your variable name first character should be in lower case, like signInUrl.

App not able to extract json data

I am trying to extract Json data, but somehow the code is not working.
Can somebody please help me ? Can't seem to understand what i am doing wrong.
(I dont really hav any more details to add)
public class MainActivity extends AppCompatActivity{
TextView t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t=(TextView)findViewById(R.id.exchangeRate);
Anindya task = new Anindya();
task.execute("xyz");
}
public class Anindya extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection=null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection)url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(System.in);
int data = reader.read();
while (data!= 0)
{
char current = (char)data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i("website content",result);
}
}
}
Try replacing InputStreamReader reader = new InputStreamReader(System.in) with InputStreamReader reader = new InputStreamReader(in)
If it still doesn't solve your problem then try to check the value of data and post details about returned value.

android async task return type and lockdown

I have the following assynctask implemented. Its usage is pretty simple, and so works as intended so far. get a url, post to it, get its contents, write them to a file. the hard part begins now
QUESTION:
I require reusage of this piece of code multiple times for multiple different files. How can i pass the file as a variable on assynctask call alongside the url?
//class to call a url and save it to a local file
private class url_to_file extends AsyncTask<String, Integer, String> {
protected String[] doInBackground(String... input) {
//function to call url and postback contents
return callpost(input[0]);
}
protected void onProgressUpdate(Integer... progress) {
//Yet to code
}
protected void onPostExecute(String result) {
//function to write content to text file
writeStringAsFile( result, "file.xml" ,getApplicationContext());
}
}
EDIT:
Purelly as reference, the function i use to read, write from file and call url
//saves a txt (etc, xml as well) file to directory,replacing previous. if directory is left empty, save to assets
public static void writeStringAsFile(final String fileContents, String fileName ,Context context) {
try {
FileWriter out = new FileWriter(new File(context.getFilesDir(), fileName));
out.write(fileContents);
out.close();
} catch (IOException e) {
}
}
//read file, returns its contents
public static String readFileAsString(String fileName,Context context) {
StringBuilder stringBuilder = new StringBuilder();
String line;
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(new File(context.getFilesDir(), fileName)));
while ((line = in.readLine()) != null) stringBuilder.append(line);
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
return stringBuilder.toString();
}
//calls a page. Returns its contents
public String callpost (String... strings)
{
StringBuilder content = new StringBuilder();
try
{
// create a url object
URL url = new URL(strings[0]);
// create a urlconnection object
URLConnection urlConnection = url.openConnection();
// wrap the urlconnection in a bufferedreader
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
// read from the urlconnection via the bufferedreader
while ((line = bufferedReader.readLine()) != null)
{
content.append(line + "\n");
}
bufferedReader.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return content.toString();
}
EDIT:
Removed second question as it had nothing to do with the rest and would just confuse people to see the thread
Kudos #FirstOne for his help up at comments
this made it for me
//class to call a url and save it to a local file
private class url_to_file extends AsyncTask<String, Integer, String> {
protected String file;
public void setFile(String input)
{
file=input;
}
protected String[] doInBackground(String... input) {
//function to call url and postback contents
return callpost(input[0]);
}
protected void onProgressUpdate(Integer... progress) {
//Yet to code
}
protected void onPostExecute(String result) {
//function to write content to text file
writeStringAsFile( result, file ,getApplicationContext());
}
}

URL validation works fine but keep connection and restrict any further requests

public class UrlVarificationTask extends AsyncTask<Void, Void, Integer> {
private String url;
private UrlVarificationDelegate delegate;
private HttpURLConnection huc;
public UrlVarificationTask(String url, UrlVarificationDelegate delegate) {
this.url = url;
this.delegate = delegate;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Integer doInBackground(Void... params) {
int responseCode = 0;
try {
System.setProperty("http.keepAlive", "false");
URL u = new URL(url);
huc = (HttpURLConnection) u.openConnection();
huc.setRequestMethod("HEAD");
huc.connect();
responseCode = huc.getResponseCode();
} catch (MalformedURLException mal) {
responseCode = -555;
} catch (IOException io) {
responseCode = -444;
} catch (Exception ex) {
responseCode = -333;
ex.printStackTrace();
}
if (huc != null) {
try {
huc.getInputStream().close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
huc.disconnect();
}
Logger.debug("Response Code==" + responseCode);
return responseCode;
}
#Override
protected void onPostExecute(Integer responseCode) {
delegate.urlVarificationResponseCode(responseCode);
super.onPostExecute(responseCode);
}
}
I used above dode for validating url,
if HEAD give me response code 200 then only I open a url to webview.
but once I call this it keep connection and not allow any other http request even after close, what to do ?
Safe use of HttpURLConnection
huc.setRequestProperty("keep-alive", "false");
this is working as HttpURLConnection keep connection alive and hence we cann't make make further request so keep-alive setting to false resolve this problem.
For properly closing the HttpURLConnection go to the link
By this URL is closed.

Categories

Resources