异步任务#1发生在doInBackground方法中 [英] Async task #1 occurring in the doInBackground method

查看:110
本文介绍了异步任务#1发生在doInBackground方法中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法确定所有的信息,然后列出我所有的三个课程。然而,在所有这些之前,我将包括我的logcat错误和我的应用程序应该做的事情:

Logcat错误



  03-27 17:10:45.368 2373-2665 / edu.ggc.amauldin.currencyappaustin E / AndroidRuntime:
致命例外:AsyncTask#1
进程:DOMAIN,PID:2373
java.lang.RuntimeException:在android.os.AsyncTask中执行doInBackground()
时发生错误$ 3.done(AsyncTask.java:304)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)$ java.util.concurrent.FutureTask.setException处的
(FutureTask.java:222)$ java.util.concurrent.FutureTask处的
。运行(FutureTask.java:242)
在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:231)
在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112 )
在java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:587)$ b $在java.lang.Thread.run(Thread.java:818)
导致: java.lang.NullPointerEx ception:试图调用虚方法
'null java.util.Scanner.close()'对一个空对象引用
在DOMAIN.FindRate.doInBackground(FindRate.java:59)
at DOMAIN.FindRate.doInBackground(FindRate.java:25)
at android.os.AsyncTask $ 2.call(AsyncTask.java:292)



应用程序应用于:



用户在EditText字段中输入值,然后选择基本货币和货币以转换为从2个纺纱厂,然后按下转换按钮,并输出新的货币。我正在尝试使用异步任务和 fixer.io 来完成此操作,希望能够学习如何更好地理解和使用它们。

课程:



我只列出我的课程,看看能否更好地阐明我的想法局势(S)。如果需要的话,我会省去我的进口等,以减少这篇文章的内容,只是让我知道。

MainActivity.java



 公共类MainActivity扩展AppCompatActivity实现AdapterView。 OnItemSelectedListener {
public static double sum;
private static String urlIO =http://api.fixer.io/latest?base=;
Spinner spinner,spinner2;
按钮convBtn,aboutBtn;

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

final EditText enteredAmt =(EditText)findViewById(R.id.editText);
final TextView result =(TextView)findViewById(R.id.resultTv);
spinner =(微调)findViewById(R.id.spinner);
spinner2 =(微调)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());

尝试{
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 \ ITEC 4550,Toast.LENGTH_SHORT).show();
}
});


$ / code $ / pre
$ b

FindRate.java



  public class FindRate extends AsyncTask< URL,Void,Double> {
private static final String rightForm =###。00;
private static final String errorCode =错误代码:它搞砸了;
private static final String checkRSP =Checking;

私人TextView tV;
私人Gson gSON;

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

}

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

HttpURLConnection connectStat = 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 =新的扫描仪(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());


$ @覆盖
保护无效onPostExecute(双重结果){
DecimalFormat格式= new DecimalFormat(rightForm);
String str = format.format(result);
tV.setText(format.format(MainActivity.sum * Double.parseDouble(str))+);


$ / code $ / pre
$ b

LookupRate.java



这是另一个我不习惯的地方,我想从fixer.io输出中获取rate(s)值,所以如果这有助于fixer.io输出的结果 {base:USD,date: 2016-03-24,rates:{GBP:0.70771}} $ b

  public class LookupRate {
private String to;
私人双倍利率;
private String from;

public Double findRate(){
return rate;

$ b @Override
public String toString(){
String str1 =Checking+
[rates =+ rate +] ;
返回str1;


$ / code $ / pre
$ b $

澄清



该应用程序在点击转换按钮时崩溃,以确保完全清除。我在这里做错了什么?

解决方案

更改

 最后{
scanner.close();
connectStat.disconnect();



<$ p $($!$ = $)$ {
if(null!= scanner){scanner.close();}
if(null!= connectStat){connectStat.disconnect();}
}

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


I can think of no way to ensure all information is given then list all three of my classes. However, before all of that I will include my logcat errors and what my app is supposed to be doing:

Logcat Errors

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)

App Is Supposed to:

User enters a value in an EditText field then picks a base currency and a currency to convert to from 2 spinners, then presses the convert button and the new currency is outputted. I'm attempting to accomplish this using async tasks and fixer.io to hopefully learn how to better understand and use them.

Classes:

I will just list out my classes to see if that will better shed some light on my situation(s). I will leave out my imports, etc. to cut down on the side of this post if they are needed just let me know.

MainActivity.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

Here is another area I'm not to comfortable with I want to just grab the rate(s) value from the fixer.io output, so if it helps this is what a fixer.io output looks like {"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;
}
 }

To Clarify

The app crashes on the click on the convert button just to make sure that was totally clear. What am I doing wrong here?

解决方案

change

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

to

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

I am guessing that an exception is thrown before scanner is initialized hence you get a Null Pointer Exception. golden rule, always check for null

这篇关于异步任务#1发生在doInBackground方法中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆