0

好的,我正在开发一个 android 应用程序。它有许多功能,例如显示新闻、星座运势、电视节目表、天气预报……每条信息都通过 RSS 使用 XML 传递给我。当我有 wifi 或 3G 时,应用程序可以正常工作,但是一旦没有 wifi 或 3G 信号,或者某些链接在维护中关闭,我就会被踢出应用程序并出现如下错误:

The application has stopped unexpectedly! Please Try Again.

我正在尝试制作一些 Activity 来显示如下内容:

There was a problem with your request! Please make sure that wifi or 3G signals are available or try again later.

我尝试了很多方法,但没有任何接缝可以工作。以下是一些可能有帮助的课程:

1.

public class Pocetna extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pocetna);
.
.
.

vijesti.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            Intent xw = new Intent(getApplicationContext(), Vijesti.class );
            xw.putExtra("A", "http://klix.ba/rss/naslovnica");
            startActivity(xw);
        }
    });

2.

public class Vijesti extends ListActivity {

static String url =null;

// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_DATE = "pubDate";
static final String KEY_DESC = "encoded";
static final String UVOD = "uvod";
static final String CLANAK = "clanak";

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.vijesti_m);
    Intent in = getIntent();

    // Get XML values from previous intent
    url = in.getStringExtra("A");
    final ArrayList<HashMap<String,String>> menuItems = new ArrayList<HashMap<String,String>>();
    ArrayList<String> xqw = new ArrayList<String>();

    ParserVijesti parser=null;
    Document doc=null;
    try {
        parser = new ParserVijesti();
        String xml = parser.getXmlFromUrl(url); //get XML
        doc = parser.getDomElement(xml);
    } catch (Exception e1) {
        finish();
    }

    NodeList nl = doc.getElementsByTagName(KEY_ITEM);
    //loop
    for (int i=0; i< nl.getLength(); i++){
        HashMap<String, String> map = new HashMap<String, String>();
        HashMap<String, String> mapq = new HashMap<String, String>();

        Element e = (Element) nl.item(i);

        //add to map
        map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
        map.put(KEY_DATE, parser.getValue(e, KEY_DATE));
        map.put(UVOD, parser.getValue(e,UVOD));
        map.put(CLANAK, parser.getValue(e,CLANAK));


        menuItems.add(map);

        xqw.add(parser.getValue(e,KEY_TITLE));
    }

    for(int gf=0; gf<xqw.size(); gf++){
        Log.w("ISPISI: ", xqw.get(gf));
    }
    ArrayAdapter adapterx = new ArrayAdapter(this, R.layout.vijesti_m,R.id.tetkica, xqw);


    setListAdapter(adapterx);

    //singleView
    ListView lv = getListView();

    lv.setOnItemClickListener(new OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id){

            int hg = position;
            HashMap<String, String> kaktus = menuItems.get(hg);
            String uvod1 = kaktus.get(UVOD);
            String clanak1 = kaktus.get(CLANAK);
            String dat1 = kaktus.get(KEY_DATE);
            String tit1 = kaktus.get(KEY_TITLE);



            //intent
            Intent inx = new Intent(getApplicationContext(), VijestiSingle.class);
            inx.putExtra(KEY_TITLE, tit1);
            inx.putExtra(KEY_DATE, dat1);
            inx.putExtra(UVOD, uvod1);
            inx.putExtra(CLANAK, clanak1);
            startActivity(inx);
        }
    });


}   

}

3.

public class ParserVijesti {


// constructor
public ParserVijesti() {

}

/**
 * Getting XML from URL making HTTP request
 * @param url string
 * */
public String getXmlFromUrl(String url) {
    String xml = null;

    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity, "UTF-8");

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // return XML
    return xml;
}
/**
 * Getting XML DOM element
 * @param XML string
 * */

public Document getDomElement(String xml){
    Document doc = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setCoalescing(true);
    dbf.setNamespaceAware(true);
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();

        InputSource is = new InputSource();
        is.setByteStream(new ByteArrayInputStream(xml.getBytes("UTF-8")));
            doc = db.parse(is); 

        } catch (ParserConfigurationException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (SAXException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (IOException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        }

        return doc;
}

/** Getting node value
  * @param elem element
  */
 public final String getElementValue( Node elem ) {
     Node child;
     if( elem != null){
         if (elem.hasChildNodes()){
             for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                 if(child.getNodeType() == Node.TEXT_NODE || child.getNodeType() == Node.CDATA_SECTION_NODE){
                     return child.getNodeValue();
                 }
             }
         }
     }
     return "";
 }

 public final String getElementValue2( Node elem ) {
     Node child;
     if( elem != null){
         if (elem.hasChildNodes()){
             for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                 if(child.getNodeType() == Node.CDATA_SECTION_NODE){
                     return child.getNodeValue();
                 }
             }
         }
     }
     return "SRANJE";
 }

 /**
  * Getting node value
  * @param Element node
  * @param key string
  * */



 public String getValue(Element item, String str) {     
        NodeList n = item.getElementsByTagName(str);                
        return this.getElementValue(n.item(0));
    }


 public String getValue3(Element item, String str){
     NodeList n = item.getElementsByTagNameNS("http://purl.org/rss/1.0/modules/content/", str);
     String ses = this.getElementValue2(n.item(0));

     //String mim =ses.replaceAll("(?s)\\<.*?\\>", " \n");
     String html = ses;
     Spanned strxa = Html.fromHtml(html);
     String fffx=strxa.toString();

     //return this.getElementValue2(n.item(0));
     //return ses;
     //return Promjena(ses);
     return fffx;
 }


}

所以基本上,我想做的不是检查是否有wifi或3G。我只想实现该 Activity 将显示存在错误并且不允许在发生错误时立即退出应用程序。请问,有人吗?

4

1 回答 1

1

要检查设备是否连接到 Wifi 或 3G,您可以创建如下方法:

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if(netInfo != null && netInfo.isConnected()) {
        return true;
    }
    return false;
}

然后,如果您尝试启动的活动依赖于互联网连接,您可以执行以下操作:

if(!isOnline) {
    Toast.makeText(getApplicationContext(), "You are not connected to the internet", Toast.LENGTH_SHORT).show();
} else {
    startActivity(*yourIntent);
}

您需要在清单中获得这些权限:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
于 2012-10-13T11:35:13.647 回答