在doinbackground方法中发生的异步任务#1

hkmswyz6  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(317)

我想不出什么办法来确保所有的信息都给出了,然后列出我的三个班级。然而,在所有这些之前,我将包括我的logcat错误和我的应用程序应该做什么:

logcat错误

03-27 17:10:45.368 2373-2665/edu.ggc.amauldin.currencyappaustin E/AndroidRuntime: 
 FATAL EXCEPTION: AsyncTask #1
Process: DOMAIN, PID: 2373
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.NullPointerException: Attempt to invoke virtual method
 'void java.util.Scanner.close()' on a null object reference
at DOMAIN.FindRate.doInBackground(FindRate.java:59)
at DOMAIN.FindRate.doInBackground(FindRate.java:25)
at android.os.AsyncTask$2.call(AsyncTask.java:292)

应用程序应该:

用户在edittext字段中输入一个值,然后从2个微调器中选择基础货币和要转换的货币,然后按convert按钮并输出新货币。我尝试使用async tasks和fixer.io来完成这个任务,希望能学习如何更好地理解和使用它们。

课程:

我将列出我的课程,看看这是否能更好地说明我的情况。我将省略我的进口等,以减少在这方面的职位,如果他们需要让我知道。

主活动.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 result = (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) {
            FindRate covertMe = new FindRate(result);
            sum = Double.parseDouble(enteredAmt.getText().toString());

            try{
                if(spinner.getSelectedItem().toString().equals("USD") && spinner2.getSelectedItem().toString().equals("EUR")){
                    covertMe.execute(new URL(urlIO + "USD&symbols=GBP"));
                }
            } catch (MalformedURLException e){
                e.printStackTrace();
            }
        }
    });
    aboutBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getBaseContext(), "By: Austin Mauldin \n ITEC 4550", Toast.LENGTH_SHORT).show();
        }
    });

}

findrate.java文件

public class FindRate extends AsyncTask<URL, Void, Double> {
private static final String rightForm = "###.00";
private static final String errorCode = "error code: it messed up";
private static final String checkRSP = "Checking";

private TextView tV;
private Gson gSON;

FindRate(TextView inp){
    tV = inp;
    gSON = new GsonBuilder().create();

}

@Override
protected Double doInBackground(URL... params) {

    HttpURLConnection connectStat = null;
    Scanner scanner = null;
    StringBuilder myJsonString = new StringBuilder();

    try {
        if (params.length != 1)
            throw new IllegalArgumentException(this.getClass().getName() + errorCode);
        connectStat = (HttpURLConnection) params[0].openConnection();
        InputStream inputer = new BufferedInputStream(connectStat.getInputStream());
        scanner = new Scanner(inputer);
        while (scanner.hasNext()) myJsonString.append(scanner.nextLine());
        Log.v(checkRSP, "Response(" + connectStat.getResponseCode() + "):" +
                connectStat.getResponseMessage());
    } catch (IOException e){
        Log.e(checkRSP, e.getStackTrace().toString());
        return Double.valueOf(-1D);
    } finally {
        scanner.close();
        connectStat.disconnect();
    }
    String jSon = myJsonString.toString();
    LookupRate cuRate = gSON.fromJson(jSon, LookupRate.class);
    Log.v(checkRSP, jSon);
    Log.v(checkRSP, cuRate.toString());
    return Double.valueOf(cuRate.findRate());

}

@Override
protected  void onPostExecute(Double result){
    DecimalFormat format = new DecimalFormat(rightForm);
    String str = format.format(result);
    tV.setText(format.format(MainActivity.sum * Double.parseDouble(str))+ "");
}
 }

lookuprate.java文件

这是另一个我不太习惯的地方,我只想从fixer.io输出中获取rate(s)值,所以如果有帮助的话,这就是fixer.io输出的样子 {"base":"USD","date":"2016-03-24","rates":{"GBP":0.70771}} ```
public class LookupRate {
private String to;
private Double rate;
private String from;

public Double findRate() {
return rate;
}

@Override
public String toString(){
String str1 = "Checking" +
" [rates=" + rate + "]";
return str1;
}
}


#### 澄清

应用程序在点击转换按钮时崩溃,只是为了确保完全清楚。我做错什么了?
x8goxv8g

x8goxv8g1#

改变

finally {
    scanner.close();
    connectStat.disconnect();
}

finally {
 if(null != scanner){   scanner.close();}
  if(null != connectStat){  connectStat.disconnect();}
 }

我猜在扫描程序初始化之前会抛出一个异常,因此会得到一个空指针异常。黄金法则,总是检查空值

相关问题