Xyz3R
Xyz3R

Reputation: 1074

download XML-File android error

I am developing an android app, and i need to download some simple XML-Files with authorization from an url. I already got something working in java on my local computer [Code at the end]. When i try to use this function in my android app, LogCat throws thousands of errors. I included Internet permission, i will attach the errors to my post. So, heres my download function. i hardcoded the base64 string, because it will not change with the time...:

    public String getXmlFromUri(String url)
{
    String strFileContents = new String("");
    try{
        String base64 = "Basic " + "hardcodedBase64String";
        URL pURL = new URL(url);
        URLConnection conn = pURL.openConnection();
        conn.setRequestProperty("Authorization", base64);
        BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));

        String data = new String("");
        while((data = in.readLine()) != null)
        {
            strFileContents += data;
        }
        in.close();
    }catch(IOException e)       {}
        if(strFileContents == "") strFileContents = "An error occured or the downloaded file was empty!";
    return strFileContents;
}

My logcat is very long, so i uploaded it at pastebin: http://pastebin.com/DhFra9SG

The function isnt finished yes, and I am currently only using it on the website where i need authorization.

To conclude: It works on windows, and it does not work on android! it

Upvotes: 0

Views: 291

Answers (2)

Raúl Omaña
Raúl Omaña

Reputation: 921

Based in your last piece of code and logcat the issue comes from the call of the Console method.

Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

Actually, you can not change/add some View object from the doInBackground method. If you want to change the UI, it must be from the onPreExecute(), onPostExecute(Result) and onProgressUpdate(Progress...) methods.

Check the AsyncTask reference, and more specifically The 4 steps section.

BR

Upvotes: 0

Andy Res
Andy Res

Reputation: 16043

Here it is:
FATAL EXCEPTION: android.os.NetworkOnMainThreadException

It crashes because you are trying to perform a network operation on UI (main) thread.
Network operations are considered to be long running operations and as a consequence they could block the UI. Thus, starting with API Level 11 if you attempt to perform a network operation on main thread, this exception is thrown.

Long running operations should run in a separate thread, for example you may use the AsyncTask to get the XML file from the server.

Upvotes: 2

Related Questions