Как скачать изображение и PDF в одной функции в Android
В Моем приложении я загружаю файлы изображений и pdf, проверяя расширение файла: если это pdf, то это означает вызов одной функции, а если это изображение, то это означает, что он вызывает другую функцию.
Теперь я хочу вызвать ту же функцию, потому что часть кода здесь одна и та же, я хочу изменить тип приложения, будь то PDF или изображение. Я отображаю данные, анализируя URL-адрес json.
Может ли кто-нибудь, пожалуйста, помогите мне, как вызвать единственную функцию, в которой я хочу скачать pdf /jpg/png?
Освещение в СМИ
public class MediaCoverage extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
//private static String url = "http://example.com/contacts";
private static String url = "http://otherexample.com/contacts";
// JSON Node names
private static final String TAG_SCHEDULES = "schedule";
private static final String TAG_ID = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_CONTENT = "content";
private static final String TAG_IMAGE = "image";
private static final String TAG_PLACE = "place";
private static final String TAG_DATETIME = "date_time";
// contacts JSONArray
JSONArray schedules = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> schedule_list;
DownloadFileFromURL task;
DownloadFileFromURL1 task1;
URLConnection conn = null;
URLConnection conn1 = null;
InputStream input = null;
private ProgressDialog pDialogD;
String imagename;
File file;
public static final int progress_bar_types = 0;
//String image1;
String fileName;
String fileNameWithoutExtn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_events_list_view);
schedule_list = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
String image = ((TextView) view.findViewById(R.id.image)).getText().toString();
//String[] str1 = image.split("/");
//imagename = str1[5].trim();
String fileName = image.substring( image.lastIndexOf('/')+1, image.length() );
String fileNameWithoutExtn = image.substring(image.lastIndexOf('.')+1);
//String ext = FilenameUtils.getExtension("/path/to/file/foo.txt");
String image1="jpg";
String image2="pdf";
if(fileNameWithoutExtn.equalsIgnoreCase(image1)){
task = (DownloadFileFromURL) new DownloadFileFromURL().execute(image);
}
else if(fileNameWithoutExtn.equalsIgnoreCase(image2)){
task1 = (DownloadFileFromURL1) new DownloadFileFromURL1().execute(image);
//Toast.makeText(getBaseContext(), "no Png images", Toast.LENGTH_LONG).show();
}
}
});
// Calling async task to get json
new GetSchedule().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetSchedule extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MediaCoverage.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
schedules = jsonObj.getJSONArray(TAG_SCHEDULES);
// looping through All Schdules
for (int i = 0; i < schedules.length(); i++) {
JSONObject c = schedules.getJSONObject(i);
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_CONTENT);
String image = c.getString(TAG_IMAGE);
String place = c.getString(TAG_PLACE);
String datetime = c.getString(TAG_DATETIME);
// Phone node is JSON Object
// tmp hashmap for Schedule
HashMap<String, String> schedule_file = new HashMap<String, String>();
// adding each child node to HashMap key => value
schedule_file.put(TAG_ID, id);
schedule_file.put(TAG_TITLE, title);
schedule_file.put(TAG_CONTENT, content);
schedule_file.put(TAG_IMAGE, image);
schedule_file.put(TAG_PLACE, place);
schedule_file.put(TAG_DATETIME, datetime);
// adding schedule list
schedule_list.add(schedule_file);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MediaCoverage.this, schedule_list,
R.layout.news_events_list_item,
new String[] { TAG_TITLE, TAG_CONTENT, TAG_IMAGE, TAG_PLACE, TAG_DATETIME },
new int[] { R.id.title,R.id.content, R.id.image, R.id.place, R.id.datetime });
setListAdapter(adapter);
}
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_types:
pDialogD = new ProgressDialog(this);
pDialogD.setMessage("Downloading file. Please wait...");
pDialogD.setIndeterminate(false);
pDialogD.setMax(100);
pDialogD.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//pDialogD.setCancelable(true);
pDialogD.show();
return pDialogD;
default:
return null;
}
}
public static File getSaveFilePath(String fileName) {
File dir = new File(Environment.getExternalStorageDirectory(), "sapthagiri");
dir.mkdirs();
File file = new File(dir, fileName);
return file;
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
@SuppressWarnings("deprecation")
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_types);
}
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
conn = (HttpURLConnection) url.openConnection();
conn.connect();
int lenghtOfFile = conn.getContentLength();
input = new BufferedInputStream(url.openStream(), 8192);
File SDCardRoot = Environment.getExternalStorageDirectory();
// String SDCardRoot = Environment.getExternalStorageDirectory().getAbsolutePath();
file = new File(SDCardRoot, "application_form.jpg");
FileOutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialogD.setProgress(Integer.parseInt(progress[0]));
}
@SuppressWarnings("deprecation")
protected void onPostExecute(String URL) {
dismissDialog(progress_bar_types);
final String imagePath = Environment.getExternalStorageDirectory().toString()+ "/application_form.jpg";
//String imagePath2 = Environment.getExternalStorageDirectory().toString() + "/school_calender.pdf";
Toast.makeText(getApplicationContext(), "Download Completed :"+imagePath, Toast.LENGTH_LONG).show();
//sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
MediaScannerConnection.scanFile(MediaCoverage.this, new String[] { file.toString() }, null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + imagePath + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "image/*");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
//application/pdf
}
}
class DownloadFileFromURL1 extends AsyncTask<String, String, String> {
@SuppressWarnings("deprecation")
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_types);
}
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
conn1 = (HttpURLConnection) url.openConnection();
conn1.connect();
int lenghtOfFile = conn1.getContentLength();
input = new BufferedInputStream(url.openStream(), 8192);
File SDCardRoot = Environment.getExternalStorageDirectory();
// String SDCardRoot = Environment.getExternalStorageDirectory().getAbsolutePath();
file = new File(SDCardRoot, "application_form.pdf");
FileOutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialogD.setProgress(Integer.parseInt(progress[0]));
}
@SuppressWarnings("deprecation")
protected void onPostExecute(String URL) {
dismissDialog(progress_bar_types);
final String imagePath = Environment.getExternalStorageDirectory().toString()+ "/application_form.pdf";
//String imagePath2 = Environment.getExternalStorageDirectory().toString() + "/school_calender.pdf";
Toast.makeText(getApplicationContext(), "Download Completed :"+imagePath, Toast.LENGTH_LONG).show();
//sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
MediaScannerConnection.scanFile(MediaCoverage.this, new String[] { file.toString() }, null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + imagePath + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
//application/pdf
}
}
public void onBackPressed() {
if (conn != null)
{
task.cancel(true);
}
else if(conn1 !=null)
{
task1.cancel(true);
}
finish();
}
}
1 ответ
Решение
Напишите ниже строку кода:
if(f_url[0].contains(".pdf"){
file = new File(SDCardRoot, "application_form.pdf");
}else{
file = new File(SDCardRoot, "application_form.jpg");
}