我有一个类Download_format,它是一个List View Activity,列出了pdf文件,我使用Async Task来填充列表。
Download_format
public class Download_format extends Activity {
JSONObject jsonobject;
JSONArray jsonarray;
ArrayList<HashMap<String, String>> arraylist;
static String url = "http://192.168.170.89/bbau_download.php";
static String down_desc = "down_desc";
static String down_url = "down_url";
ListView listview;
DownloadListViewAdapter adapter;
@Override
public void onCreate(Bundle savedInstantState) {
super.onCreate(savedInstantState);
// Get the view from listview_main.xml
setContentView(R.layout.down_layout);
if (url != null && url.trim().length() > 0) {
//System.out.println("Before exec: "+url);
new DownloadJSON().execute(url);
}
}
private class DownloadJSON extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
String url1 = params[0];
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL(url1);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("Download");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
System.out.println(jsonobject.getString("Down_desc"));
System.out.println(jsonobject.getString("Down_link"));
map.put("down_desc", jsonobject.getString("Down_desc"));
map.put("down_url", jsonobject.getString("Down_link"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.down_list);
//listview.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this).color(Color.BLACK).build());
// Pass the results into ListViewAdapter.java
adapter = new DownloadListViewAdapter(Download_format.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
}
}
}
此活动的Adapter类如下:
public class DownloadListViewAdapter extends BaseAdapter {
public static final int progress_bar_type = 0;
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
static int Down=0;
private ProgressDialog pDialog = null;
private static final int MEGABYTE = 1024 * 1024;
public DownloadListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView down_desc;
TextView down_url;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.down_format_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
down_desc = (TextView) itemView.findViewById(R.id.down_text);
down_url = (TextView) itemView.findViewById(R.id.down_url);
// Capture position and set results to the TextViews
down_desc.setText(resultp.get(Download_format.down_desc));
down_url.setText(resultp.get(Download_format.down_url));
// Capture ListView item click
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
new DownloadFile().execute(resultp.get(Download_format.down_url), resultp.get(Download_format.down_desc+".pdf"));
}
});
return itemView;
}
我想点击listview项目下载pdf文件 在上面的Base适配器类中,我包含下面的Asynclass来下载pdf
ASync Class
private class DownloadFile extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
@Override
protected String doInBackground(String... strings) {
String fileUrl = strings[0]; // -> http://maven.apache.org/maven-1.x/maven.pdf
String fileName = strings[1]; // -> maven.pdf
File pdfFile = null;
//if there is no SD card, create new directory objects to make directory on device
if (Environment.getExternalStorageState() == null) {
System.out.println("SD card not installed");
//create new file directory object
String extStorageDirectory = Environment.getDataDirectory().toString();
File folder = new File(extStorageDirectory, "BBAU_Downloads");
System.out.println(extStorageDirectory);
if (folder.exists()) {
File[] dirFiles = folder.listFiles();
if (dirFiles.length != 0) {
for (int ii = 0; ii < dirFiles.length; ii++) {
if(dirFiles[ii].getName().equals(fileName)){
System.out.println("File is present");
pDialog.dismiss();
Down=1;}
}
}
}
if (!folder.exists()) {
folder.mkdir();
}
pdfFile = new File(folder, fileName);
try {
pdfFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}else if(Environment.getExternalStorageState() != null){
System.out.println("SD card installed");
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "MCAcourse");
System.out.println(extStorageDirectory);
if (folder.exists()) {
File[] dirFiles = folder.listFiles();
System.out.println(dirFiles.length);
if (dirFiles.length != 0) {
for (int ii = 0; ii < dirFiles.length; ii++) {
Log.d("PDF name:", dirFiles[ii].getName());
if(dirFiles[ii].getName().equals(fileName)){
System.out.println("File is present");
pDialog.dismiss();
Down=1;
}
}
}
}
if (!folder.exists()) {
folder.mkdir();
}
pdfFile = new File(folder, fileName);
try {
pdfFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if(Down==0) {
try {
System.out.println(Down);
System.out.println("In Download file");
URL url = new URL(fileUrl);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(pdfFile);
int totalSize = urlConnection.getContentLength();
System.out.println(totalSize);
byte[] buffer = new byte[MEGABYTE];
long total = 0;
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
if (isCancelled()) {
inputStream.close();
return null;
}
total += bufferLength;
// publishing the progress....
if (totalSize > 0) // only if total length is known
publishProgress("" + (int) ((total * 100) / totalSize));
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
} catch (FileNotFoundException e) {
System.out.println("Some error");
e.printStackTrace();
} catch (MalformedURLException e) {
System.out.println("Some error occured");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Some error occured again");
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String s){
File pdfFile = null;
if(Environment.getExternalStorageDirectory()!=null) {
pdfFile = new File(Environment.getExternalStorageDirectory() + "/MCAcourse/" + "syllabus.pdf"); // -> filename = maven.pdf
}else if(Environment.getExternalStorageDirectory()==null){
pdfFile = new File(Environment.getDataDirectory() + "/MCAcourse/" + "syllabus.pdf");
}
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(DownloadListViewAdapter.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
if (Integer.parseInt(progress[0]) >= 100) {
// close the progress bar dialog
pDialog.dismiss();
}
}
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file..");
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(false);
pDialog.show();
return pDialog;
default:
return null;
}
}
我想知道这种方式是否正确,因为我收到的错误为&#34;无法解析startActivity&#34;在
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(DownloadListViewAdapter.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
或者,如果有其他方式我可以点击列表视图项目下载pdf文件...请帮忙。