没有互联网连接或没有从URL获取任何值时Android应用程序崩溃

时间:2016-02-24 07:43:04

标签: android exception-handling currency-exchange-rates

我正在使用yahoo finance api将货币数据提取到我的Android应用程序中。我正在开发转换器应用程序。我的问题是 - 当没有连接时,我的应用程序被强制停止或崩溃,即引发了一些异常,但我无法放置代码来处理这些异常。我试过但我失败了。我请你们帮助我。这是下面给出的代码 -

stole it

3 个答案:

答案 0 :(得分:1)

在我的应用中实施支票后,查看是否有任何互联网连接。 您可以查看此内容并决定是否要实现此目的。

public class ConnectionDetector {

private Context context;

public ConnectionDetector(Context cont){
    this.context = cont;
}

public boolean isConnectingToInternet(){
    ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null)
    {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }

    }
    return false;
}
}

您可以在OnCreate方法中初始化此类的对象。

最后在触发AsyncTask之前调用此类'方法。

Boolean isInternetConnected = cd.isConnectingToInternet();
if (isInternetConnected)
{
   //execute AsyncTask here.
}

希望这有帮助。

答案 1 :(得分:0)

  

如果未添加,请添加清单权限:

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


     public void Currency() {
        spin_currency = (Spinner) findViewById(R.id.myspin);
        toSpin_currency = (Spinner) findViewById(R.id.myspin1);

        ArrayAdapter<CharSequence> adapterC = ArrayAdapter.createFromResource(this, R.array.name,
                android.R.layout.simple_spinner_item);
        adapterC.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
        spin_currency.setAdapter(adapterC);
        toSpin_currency.setAdapter(adapterC);
        spin_currency.setOnItemSelectedListener(new spinOne(1));
        toSpin_currency.setOnItemSelectedListener(new spinOne(2));
        btnConv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               /* if (etInput.getText().toString().trim().length() > 0) {
                    double cur = Double.parseDouble(etInput.getText().toString()); */
                if (from == to) {
                    Toast.makeText(getApplicationContext(), "Invalid conversion", Toast.LENGTH_LONG).show();
                    etOutput.setText(null);
                } else {
                  if(Helper.isConnectingToInternet(context)){

                      new DownloadData().execute();
                  }else{

                      // Print message for No Internet Connection !

                  }

               }
           }
        });
    }
  

将此方法添加到Utility Class:

 /**
     * @param context
     * @return
     */
    public static boolean isConnectingToInternet(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {

            NetworkInfo[] info = connectivity.getAllNetworkInfo();

            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
        }
        return false;
    }

希望它会对你有所帮助!

答案 2 :(得分:0)

首先,如果没有可用的网络,您应该保护asynctask电话:

if(isNetworkAvailable)
{
  new DownloadData().execute();
}else{
  //Show a toast that no network is available
}

然后在asynctask中你应该检查 s是否为空,如:

  s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22" + val[from] + val[to] + "%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");

    if(s!=null){
                    JSONObject jObj;
                    jObj = new JSONObject(s);
                    exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");

                    System.out.println(exResult);
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    }else{
     //Show a toast
    }
   return exResult;
    }

保护 onPostExecute 以及:

if( exResult!=null || !exResult.equals("")){
 System.out.println("theResult:" + exResult);
        if(etInput.getText().toString().trim().length() > 0 ){
            if (etInput.getText().toString().equals(".") || etInput.getText().toString().equals("-.") || etInput.getText().toString().equals("-")) {
                Toast.makeText(getApplicationContext(), "Please enter a valid value", Toast.LENGTH_LONG).show();
            } else {
                Double cur = Double.parseDouble(etInput.getText().toString());
                etOutput.setText(String.valueOf(Double.parseDouble(exResult) * cur));
            }
        } else {
            Toast.makeText(getApplicationContext(), "Please enter a valid value", Toast.LENGTH_LONG).show();
            etOutput.setText(null);
        }
    }
}