Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8964321
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T16:33:42+00:00 2026-06-15T16:33:42+00:00

So i have this parsing code set up, and i’m getting the NetworkOnMainThreadException, so

  • 0

So i have this parsing code set up, and i’m getting the NetworkOnMainThreadException, so I wanted to wrap it in an AsyncTask, but i’m not sure what to put and where to put it..

I already read a couple of tutorials on AsyncTask but they are all kind of confusing, i was wondering if anyone could point out where i should put the blocks i have now:

Noticias.java (MainActivity):

public class Noticias extends ListActivity {



static final String URL = "http://loc.grupolusofona.pt/index.php/?format=feed";

static final String KEY_ITEM = "item"; 
static final String KEY_TITLE = "title";
static final String KEY_DESC = "description";
static final String KEY_LINK = "link";
static final String KEY_PUBDATE = "pubDate";

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

    ArrayList<HashMap<String, Spanned>> menuItems = new ArrayList<HashMap<String, Spanned>>();

    XMLParser parser = new XMLParser(); 
    String xml = parser.getXmlFromUrl(URL);
    Document doc = parser.getDomElement(xml); 

    NodeList nl = doc.getElementsByTagName(KEY_ITEM);

    String data[] = new String[nl.getLength()];

    for (int i = 0; i < nl.getLength(); i++) {

        HashMap<String, Spanned> map = new HashMap<String, Spanned>();
        Element e = (Element) nl.item(i);

        //Date Conversion
        data[i] = getTagValue("pubDate", e);
        SimpleDateFormat sdf = new SimpleDateFormat("EE, dd MMM yyyy HH:mm:ss z", Locale.UK);
        Date date = null;

        try {
            date = sdf.parse(data[i]); 
            String timeOfDay = new SimpleDateFormat("HH:mm").format(date); 
            java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
            java.sql.Timestamp timeStampNow = new Timestamp((new java.util.Date()).getTime()); 

            long secondDiff = timeStampNow.getTime() / 1000 - timeStampDate.getTime() / 1000;
            int minuteDiff = (int) (secondDiff / 60);
            int hourDiff = (int) (secondDiff / 3600);
            int dayDiff = daysBetween(date, new Date()); 
            if (dayDiff > 0) {
                System.out.println("Há " + dayDiff + " dia(s), às " + timeOfDay); 
                data[i] = ("Há " + dayDiff + " dia(s), às " + timeOfDay);


            } else if (hourDiff > 0) {
                System.out.println("Há " + hourDiff + " hora(s), às " + timeOfDay);
                data[i] = ("Há " + hourDiff + " hora(s), às " + timeOfDay);


            } else if (minuteDiff > 0) {
                System.out.println("Há " + minuteDiff + " minuto(s), às " + timeOfDay);
                data[i] = ("Há " + minuteDiff + " minuto(s), às " + timeOfDay);


            } else if (secondDiff > 0) {
                System.out.println("Há " + secondDiff + " segundo(s), às " + timeOfDay);
                data[i] = ("Há " + secondDiff + " segundo(s), às " + timeOfDay);

            }
        } catch (ParseException e1) {
            e1.printStackTrace();
        } catch (java.text.ParseException e1) {
            e1.printStackTrace();
        }

        //Html.fromHtml to get <CDATA> Description          
        map.put(KEY_TITLE, Html.fromHtml(parser.getValue(e, KEY_TITLE)));
        map.put(KEY_DESC, Html.fromHtml(parser.getValue(e, KEY_DESC)));
        map.put(KEY_PUBDATE, Html.fromHtml(data[i]));
        map.put(KEY_LINK, Html.fromHtml(parser.getValue(e, KEY_LINK)));

        menuItems.add(map);

    } //endFOR


    //Using ListAdapter is enough for this, no need for Custom Adapter
    ListAdapter adapter = new SimpleAdapter(this, menuItems, R.layout.linhafeed, 
            new String[] { KEY_TITLE, KEY_DESC, KEY_PUBDATE, KEY_LINK },
            new int[] { R.id.title, R.id.desc, R.id.pub, R.id.link });

    setListAdapter(adapter);


    ListView lv = getListView();

    //Opening Link onClick
    lv.setOnItemClickListener(new OnItemClickListener() {

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

            String link = ((TextView) view.findViewById(R.id.link)).getText().toString();
            System.out.println("Link: " + link);
            Intent in = new Intent(Intent.ACTION_VIEW);
            in.setData(Uri.parse(link));
            startActivity(in);
        }
    });


}

private static String getTagValue(String sTag, Element e) { 
    NodeList nlList = e.getElementsByTagName(sTag).item(0).getChildNodes();
    Node nValue = (Node) nlList.item(0);
    return nValue.getNodeValue();
}

public static int daysBetween(Date startDate, Date endDate) { 

    int daysBetween = 0;
    while (startDate.before(endDate)) {
        startDate.setTime(startDate.getTime() + 86400000);
        daysBetween++;
    }
    return daysBetween;

}
}

And the XMLParser.java:

public class XMLParser {

// constructor
public XMLParser() {

}

/**
 * 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);

    } 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();
    try {

        DocumentBuilder db = dbf.newDocumentBuilder();

        InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            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 ) {

     if( elem != null){
         return elem.getTextContent();
             }


     return "";
 }

 /**
  * 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));
    }
}

Thanks for your time.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T16:33:43+00:00Added an answer on June 15, 2026 at 4:33 pm

    Simply you should put the part that do the connection in the doInBackground and the part that modify the ui in the onPostExecute..

    Example (need to be checked carefully):

    private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
    
      private Context context;
    
     public DownloadFilesTask(Context context) {
        this.context = context;
     }
    
     protected void onPreExecute() {
             progressDialog = ProgressDialog.show(context, "", "msg", true); 
     }
     protected Long doInBackground(URL... urls) {
         XMLParser parser = new XMLParser(); 
    String xml = parser.getXmlFromUrl(URL);
    Document doc = parser.getDomElement(xml); 
    
    NodeList nl = doc.getElementsByTagName(KEY_ITEM);
    
    String data[] = new String[nl.getLength()];
    
    for (int i = 0; i < nl.getLength(); i++) {
    
        HashMap<String, Spanned> map = new HashMap<String, Spanned>();
        Element e = (Element) nl.item(i);
    
        //Date Conversion
        data[i] = getTagValue("pubDate", e);
        SimpleDateFormat sdf = new SimpleDateFormat("EE, dd MMM yyyy HH:mm:ss z", Locale.UK);
        Date date = null;
    
        try {
            date = sdf.parse(data[i]); 
            String timeOfDay = new SimpleDateFormat("HH:mm").format(date); 
            java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
            java.sql.Timestamp timeStampNow = new Timestamp((new java.util.Date()).getTime()); 
    
            long secondDiff = timeStampNow.getTime() / 1000 - timeStampDate.getTime() / 1000;
            int minuteDiff = (int) (secondDiff / 60);
            int hourDiff = (int) (secondDiff / 3600);
            int dayDiff = daysBetween(date, new Date()); 
            if (dayDiff > 0) {
                System.out.println("Há " + dayDiff + " dia(s), às " + timeOfDay); 
                data[i] = ("Há " + dayDiff + " dia(s), às " + timeOfDay);
    
    
            } else if (hourDiff > 0) {
                System.out.println("Há " + hourDiff + " hora(s), às " + timeOfDay);
                data[i] = ("Há " + hourDiff + " hora(s), às " + timeOfDay);
    
    
            } else if (minuteDiff > 0) {
                System.out.println("Há " + minuteDiff + " minuto(s), às " + timeOfDay);
                data[i] = ("Há " + minuteDiff + " minuto(s), às " + timeOfDay);
    
    
            } else if (secondDiff > 0) {
                System.out.println("Há " + secondDiff + " segundo(s), às " + timeOfDay);
                data[i] = ("Há " + secondDiff + " segundo(s), às " + timeOfDay);
    
            }
        } catch (ParseException e1) {
            e1.printStackTrace();
        } catch (java.text.ParseException e1) {
            e1.printStackTrace();
        }
    
        //Html.fromHtml to get <CDATA> Description          
        map.put(KEY_TITLE, Html.fromHtml(parser.getValue(e, KEY_TITLE)));
        map.put(KEY_DESC, Html.fromHtml(parser.getValue(e, KEY_DESC)));
        map.put(KEY_PUBDATE, Html.fromHtml(data[i]));
        map.put(KEY_LINK, Html.fromHtml(parser.getValue(e, KEY_LINK)));
    
        menuItems.add(map);
    
    } //endFOR
     }
    
     protected void onPostExecute(Long result) {
         progressDialog.dismiss();  
    
         //Using ListAdapter is enough for this, no need for Custom Adapter
    ListAdapter adapter = new SimpleAdapter(this, menuItems, R.layout.linhafeed, 
            new String[] { KEY_TITLE, KEY_DESC, KEY_PUBDATE, KEY_LINK },
            new int[] { R.id.title, R.id.desc, R.id.pub, R.id.link });
    
    setListAdapter(adapter);
     }
    }
    

    OnCreate:

    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_noticias);
    
    ArrayList<HashMap<String, Spanned>> menuItems = new ArrayList<HashMap<String, Spanned>>
    ();
       new DownloadFilesTask(this).execute();
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

SO I have the following set of code parsing delicious information. It prints data
SO I have the following set of code parsing delicious information. It prints data
I have this code below. As you can see I am passing two variables
I have student.xml file and am parsing this file using SAX Parser and now
I am parsing an html content and have output on my screen. This website
I have this strange problem parsing XML document in PHP loaded via cURL. I
I have this strange problem in JQuery. I try to set a value to
I have this setting in my web config: <globalization culture=auto uiCulture=auto/> The code is
I have this code: while($row = mysql_fetch_array($res)) { $name = $row['advertiser']; $id = $row['id'];
I have this class... public class MyDTO { public int Id { get; set;

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.