gpt4 book ai didi

java - 使用 AsyncTask 显示进度时下载文件时出错

转载 作者:行者123 更新时间:2023-11-30 00:34:11 24 4
gpt4 key购买 nike

我用了这个Answer开发 Android 应用程序以从互联网服务器下载文件。

但它给出了以下错误。

error: expected

error: illegal start of type

Execution failed for task ':app:compileDebugJavaWithJavac'.

Compilation failed; see the compiler error output for details.

这个错误是针对代码行的,

downloadTask.execute("the url to the file you want to download");//execute method
//is highlighted in red in android studio and it says "Cannot resolve symbol execute"

这个答案被认为是正确的。我按照它说的做了,但它仍然给出上述错误。我对这个环境很陌生,请帮助我。

 package com.kalusudu.dp.smarthike;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PowerManager;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class RecentStories extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recent_stories);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});

TextView text1 = (TextView) findViewById(R.id.TextView01);
text1.setText("Knuckles mountain range is a part of the Hill Country of Sri Lanka which is also about 3000 Ft or 915 Mts. from sea level and covers an area of about 90 Sq. Milles or 234 Sq. Km of land extent.");

TextView text2 = (TextView) findViewById(R.id.TextView02);
text2.setText("Knuckles mountain range is a part of the Hill Country of Sri Lanka which is also about 3000 Ft or 915 Mts. from sea level and covers an area of about 90 Sq. Milles or 234 Sq. Km of land extent.");


ImageView imageviewOne = (ImageView) findViewById(R.id.imageView01);
imageviewOne.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(RecentStories.this,Cloud.class);
//intent.setAction(Intent.ACTION_VIEW);
//intent.addCategory(Intent.CATEGORY_BROWSABLE);
//intent.setData(Uri.parse("http://m.facebook.com"));
startActivity(intent);
}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_recent_stories, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}

// execute this when the downloader must be fired
final DownloadTask downloadTask = new DownloadTask(RecentStories.this);
downloadTask.execute("URL");//execute method
//is highlighted in red in android studio and it says "Cannot resolve symbol execute"


}

// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
private class DownloadTask extends AsyncTask<String, Integer, String> {

private Context context;
private PowerManager.WakeLock mWakeLock;

public DownloadTask(Context context) {
this.context = context;
}

@Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();

// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}

// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();

// download the file
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/file_name.extension");

byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}

if (connection != null)
connection.disconnect();
}
return null;
}

@Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
}

@Override
protected void onProgressUpdate(Integer... progress) {
}

@Override
protected void onPostExecute(String result) {
mWakeLock.release();
if (result != null)
Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
}
}

最佳答案

你添加了你的 url - 还是只添加了文本???

downloadTask.execute("the url to the file you want to download");

例如

downloadTask.execute("https://maps.awesome.com/maps/api/geocode/json");

关于java - 使用 AsyncTask 显示进度时下载文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43693004/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com