java - 异步任务错误 #1 和 Internet 权限

标签 java android asynchronous

我一直遇到同样的异步错误,所以我想我应该根据我在 post 中使用的代码来修改我的代码昨天,但是我仍然遇到同样的问题。 我会在下面发布我的 logcat 和 2 个类(class),如果您看到我遗漏的内容,请告诉我。

日志

32621-509/edu.ggc.amauldin.currencyappaustin E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: DOMAIN, PID: 32621
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:304)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)  
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
at java.net.InetAddress.lookupHostByName(InetAddress.java:451)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:332)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:199)
at MYDOMAIN.FetchConversionRateTask.doInBackground(FetchConversionRateTask.java:46)
at MYDOMAIN.FetchConversionRateTask.doInBackground(FetchConversionRateTask.java:24)

FetchConversionRateTask.java

public class FetchConversionRateTask extends AsyncTask<String, String, Double> {
private static final String CONV_LOOKUP = "ConversionLookup";
private TextView txtView;
private Gson gson;

FetchConversionRateTask(TextView _t) {
    txtView = _t;
    gson = new GsonBuilder().create();
}
@Override
protected Double doInBackground(String... currencies) {
    String from = currencies[0];
    String to = currencies[1];

    Scanner scanner = null;
    HttpURLConnection conn = null;
    StringBuilder jsonSB;
    try{
        URL url = new URL("http://api.fixer.io/latest?base=USD&symbols=" + from + "," + to);
        jsonSB = new StringBuilder();
        publishProgress("opening connection");
        conn = (HttpURLConnection) url.openConnection();
        InputStream in = new BufferedInputStream(conn.getInputStream());
        scanner = new Scanner(in);
        // process entire stream
        while (scanner.hasNext()) jsonSB.append(scanner.nextLine());
        String msg = "(" + conn.getResponseCode() +  "):" + conn.getResponseMessage();
        Log.v(CONV_LOOKUP, "Response" + msg);
        publishProgress(msg);
    } catch (IOException e){
        Log.e(CONV_LOOKUP, e.getMessage());
        return  Double.valueOf(-1.0D);
    } finally {
        if(scanner != null) scanner.close();
        if (conn != null) conn.disconnect();
    }
    Double rate = null;
    try {
        rate = new JSONObject(jsonSB.toString()).getJSONObject("rates").getDouble(to);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    Log.v(CONV_LOOKUP, jsonSB.toString());
    return Double.parseDouble(rate.toString());
}

protected void onProgressUpdate(String status){
    txtView.setText(status);
}

@Override
protected void onPostExecute(Double result){
    txtView.setText(new DecimalFormat("###.####").format(result));
}

主 Activity .java

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
public static double sum;
private static String urlIO = "http://api.fixer.io/latest?base=";
Spinner spinner, spinner2;
Button convBtn, aboutBtn;

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

    final EditText enteredAmt = (EditText)findViewById(R.id.editText);
    final TextView rslt = (TextView)findViewById(R.id.resultTv);
    spinner = (Spinner) findViewById(R.id.spinner);
    spinner2 = (Spinner) findViewById(R.id.spinner2);
    convBtn = (Button) findViewById(R.id.button);
    aboutBtn = (Button) findViewById(R.id.button2);

    ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.currencyTypes, android.R.layout.simple_spinner_item);
    spinner.setAdapter(adapter);
    spinner2.setAdapter(adapter);

    spinner.setOnItemSelectedListener(this);
    spinner2.setOnItemSelectedListener(this);

    convBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FetchConversionRateTask task = new FetchConversionRateTask(rslt);
            rslt.setText("fetching...");
            sum = Double.parseDouble(enteredAmt.getText().toString());

                if(spinner.getSelectedItem().toString().equals("USD") && spinner2.getSelectedItem().toString().equals("EUR")){
                    task.execute("USD", "EUR");
                }


        }
    });
    aboutBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getBaseContext(), "...", Toast.LENGTH_SHORT).show();
        }
    });

}

最佳答案

异常

Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)

必须在manifest.xml中添加internet权限否则会报错

<uses-permission android:name="android.permission.INTERNET"/>

下面的不是访问互联网所必需的,但在执行您的请求之前检查网络状态很有用

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

关于java - 异步任务错误 #1 和 Internet 权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36267671/

相关文章:

android - Sqlite DB with Android 一些基本问题

grails - 带有HttpSession的Grails异步请求的行为异常

java - 使用 xpath 读取多个 XML 属性

java - java中的抽象与抽象

android - Intellij IDEA Android 预览不起作用

Android Widget Upgrade app..删除小部件

unit-testing - Dart 单元测试应该在异常时失败

javascript - 了解 javascript 回调和形式参数

java - Java的静态全局变量在函数中使用时会改变其值而不返回吗?

java - 继承会破坏封装吗?