Search code examples
androidandroid-activityandroid-2.3-gingerbread

The application has stopped unexpectedly, specific case on android


Ok, I am working on one android application. It has many features, such as showing the News, Horoscope, TV schedule, Weather forecast ... Every piece of information is comming to me through RSS, using XML. Application works as it is supposed to do when I have wifi or 3G, but as soon as there is no wifi or 3G signal, or some of the links are down under maintenance I get kicked out of application and error like:

The application has stopped unexpectedly! Please Try Again.

I was trying to make some Activity that will show something like:

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

I've tried many ways but nothing seams to work. Here are a few classes that might help:

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;
 }


}

So basically, what I want to do is not to check whether there is or not wifi or 3G. I just want to implement that Activity that will show that there is an error and not allow instantly kicking out of application whenever error occures. Please, anyone?


Solution

  • To check if the device is connected to Wifi or 3G, you could create a method like this:

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

    Then, if the Activity you are trying to launch is dependent on internet connection, you could do:

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

    You'll need these permissions in your manifest:

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