0

activity code:

package com.example.ma18uus.myapplication;

import java.io.IOException;
import java.io.InputStream;

import java.net.URL;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;




public class weatherAPI {


    public static void main() throws Exception {

        //Main url
        String main_url = "http://api.weatherapi.com/v1/";

        //Live or Weekly forecast
        String live_weather = "current.xml?key=";
        //String sevendays_weather = "orecast.xml?key=";

        //API Key + q
        String API_Key = "APIKEY&q=";

        //Location Setters
        String location = "London";


        InputSource inSource = null;
        InputStream in = null;

        XMLReader xr = null;

        try
        {
            // Turn the string into a URL object
            String complete_url = main_url + live_weather + API_Key + location;
            URL urlObject = new URL(complete_url);

            // Open the stream (which returns an InputStream):
            in = urlObject.openStream();

            /** Now parse the data (the stream) that we received back ***/

            // Create an XML reader
            SAXParserFactory parserFactory = SAXParserFactory.newInstance();
            SAXParser parser = parserFactory.newSAXParser();
            xr = parser.getXMLReader();

            // Tell that XML reader to use our special Google Handler
            Handler ourSpecialHandler = new Handler();
            xr.setContentHandler(ourSpecialHandler);

            // We have an InputStream, but let's just wrap it in
            // an InputSource (the SAX parser likes it that way)
            inSource = new InputSource(in);

            // And parse it!
            xr.parse(inSource);

        }
        catch(IOException ioe)
        {
            ioe.printStackTrace();
        }
        catch(SAXException se)
        {
            se.printStackTrace();
        }

    }
}

weatherView class:

package com.example.ma18uus.myapplication;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.widget.TextView;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.InputStream;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;


public class weatherView extends AppCompatActivity {


    //Main url
    static final String main_url = "http://api.weatherapi.com/v1/";
    //Live or Weekly forecast
    static final String live_weather = "current.xml?key=";
    //String sevendays_weather = "orecast.xml?key=";
    //API Key + q
    static final String API_Key = "c3bdfadb90d5452bb8003318201801&q=";
    //Location Setters
    static final String location = "London";

    //Complete url for todays forecast
    static final String URLT = main_url + live_weather + API_Key + location;

    //XML node keys
    static final String KEY_ITEM = "root";//parent node
    static final String KEY_NAME = "name";//name of city, string
    static final String KEY_WIND_MPH = "wind_mph";//wind mph, float
    static final String KEY_WIND_KPH = "wind_kph";//wind kph, float
    static final String KEY_C = "temp_c";//Temperature Celsius, int
    static final String KEY_C_FEELS = "feelslike_c";//Temperature feeling Celsius, float
    static final String KEY_F = "temp_f";//Temperature Fahrenheit, int
    static final String KEY_F_FEELS = "feelslike_f";//Temperature feeling Fahrenheit, float
    static final String KEY_HUMIDITY = "humidity";//Humidity Level, int
    static final String KEY_CONDITION_TEXT = "text";//Weather Condition i.e. cloudy, sunny, clear, string


    ArrayList<HashMap<String, String>> menuItems;

    private TextView txt;
    String xml;

    //@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather_view);

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

        txt = (TextView) findViewById(R.id.weather_window);

        new weatherTask().execute();
       // weatherTask.parseXML();
    }

    private class weatherTask extends AsyncTask<Void, Void, Void>{


        @Override
        protected Void doInBackground(Void... voids) {
            parseXML();
            return null;
        }

        private void parseXML(){


            XmlPullParserFactory parserFactory;
            try {
                parserFactory = XmlPullParserFactory.newInstance();
                XmlPullParser parser = parserFactory.newPullParser();
                try {
                    InputStream is = new URL(URLT).openStream();
                    parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
                    parser.setInput(is, null);

                    processParsing(parser);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (XmlPullParserException e) {
                e.printStackTrace();
            }

        }

        private void processParsing(XmlPullParser parser) throws IOException, XmlPullParserException{

            ArrayList<WeatherConditions> weather = new ArrayList<>();
            int eventType = parser.getEventType();
            WeatherConditions currentWeather = null;

            while(eventType != XmlPullParser.END_DOCUMENT){

                String sName = null;

                switch(eventType){
                    case XmlPullParser.START_TAG:
                        sName = parser.getName();

                        if ("root".equals(sName)){
                            currentWeather = new WeatherConditions();
                            weather.add(currentWeather);
                        }else if (currentWeather != null){
                            if ("name".equals(sName)){
                                currentWeather.name = parser.nextText();
                            }
                            else if ("wind_mph".equals(sName)){
                                currentWeather.wind_mph = parser.nextText();
                            }else if ("wind_kph".equals(sName)){
                                currentWeather.wind_kph = parser.nextText();
                            }else if ("celsius".equals(sName)){
                                currentWeather.celsius = parser.nextText();
                            }else if ("feelsCelsius".equals(sName)){
                                currentWeather.feelsCelsius = parser.nextText();
                            }else if ("fahrenheit".equals(sName)){
                                currentWeather.fahrenheit = parser.nextText();
                            }else if ("feelsFahrenheit".equals(sName)){
                                currentWeather.feelsFahrenheit = parser.nextText();
                            }else if ("humidity".equals(sName)){
                                currentWeather.humidity = parser.nextText();
                            }else if ("text".equals(sName)){
                                currentWeather.condition_text = parser.nextText();
                            }
                        }
                        break;
                }

                eventType = parser.next();
            }

            printWeather(weather);
        }

        private void printWeather(ArrayList<WeatherConditions> weather){

            StringBuilder builder = new StringBuilder();

            for (WeatherConditions weatherC : weather){

                builder.append(weatherC.name).append("\n").append(weatherC.wind_mph).append("\n").append(weatherC.wind_kph).append("\n").append(weatherC.celsius).append("\n").append(weatherC.feelsCelsius).
                        append("\n").append(weatherC.fahrenheit).append("\n").append(weatherC.feelsFahrenheit).append("\n").append(weatherC.humidity).append("\n").append(weatherC.condition_text).append("\n");

            }

            txt.setText(builder.toString());
        }

    }

}

current manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.ma18uus.myapplication">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:networkSecurityConfig="@xml/network_security_config"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true">
        <meta-data
            android:name="com.google.android.actions"
            android:resource="@xml/network_security_config" />

        <activity android:name=".weatherView" />
        <activity android:name=".ClothesApp">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".HoodiesSweatShirts" />
        <activity android:name=".CoatsJackets" />
        <activity android:name=".Shirts" />
        <activity android:name=".Trousers" />
        <activity android:name=".Shoes" />
        <activity android:name=".Accessories" />
    </application>

</manifest>

Current Error output:

01/24 16:15:28: Launching 'app' on Pixel 2 API 29.
$ adb shell am start -n "com.example.ma18uus.myapplication/com.example.ma18uus.myapplication.ClothesApp" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Waiting for process to come online...
Connected to process 22318 on device 'Pixel_2_API_29 [emulator-5554]'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/s.myapplicatio: Not late-enabling -Xcheck:jni (already on)
W/main: type=1400 audit(0.0:268): avc: granted { read } for name="u:object_r:net_dns_prop:s0" dev="tmpfs" ino=8398 scontext=u:r:untrusted_app_25:s0:c512,c768 tcontext=u:object_r:net_dns_prop:s0 tclass=file
E/s.myapplicatio: Unknown bits set in runtime_flags: 0x8000
W/s.myapplicatio: Unexpected CPU variant for X86 using defaults: x86
I/s.myapplicatio: The ClassLoaderContext is a special shared library.
D/libEGL: Emulator has host GPU support, qemu.gles is set to 1.
W/libc: Unable to set property "qemu.gles" to "1": connection failed; errno=13 (Permission denied)
W/RenderThread: type=1400 audit(0.0:269): avc: denied { write } for name="property_service" dev="tmpfs" ino=8445 scontext=u:r:untrusted_app_25:s0:c512,c768 tcontext=u:object_r:property_socket:s0 tclass=sock_file permissive=0
D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
W/s.myapplicatio: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/s.myapplicatio: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
D/HostConnection: HostConnection::get() New Host Connection established 0xdc973fa0, tid 22351
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0 
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/eglCodecCommon: setVertexArrayObject: set vao to 0 (0) 0 0
D/EGL_emulation: eglCreateContext: 0xe7fa9ac0: maj 3 min 0 rcv 3
D/EGL_emulation: eglMakeCurrent: 0xe7fa9ac0: ver 3 0 (tinfo 0xe7fe50e0)
W/Gralloc3: mapper 3.x is not supported
D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0xdc975cb0, tid 22351
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0 
D/eglCodecCommon: allocate: Ask for block of size 0x1000
    allocate: ioctl allocate returned offset 0x3ff805000 size 0x2000
D/EGL_emulation: eglMakeCurrent: 0xe7fa9ac0: ver 3 0 (tinfo 0xe7fe50e0)
D/eglCodecCommon: setVertexArrayObject: set vao to 0 (0) 1 0
W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@dffd53e
D/NetworkSecurityConfig: Using Network Security Config from resource network_security_config debugBuild: true
W/System.err: java.net.SocketException: socket failed: EPERM (Operation not permitted)
W/System.err:     at java.net.Socket.createImpl(Socket.java:492)
W/System.err:     at java.net.Socket.getImpl(Socket.java:552)
        at java.net.Socket.setSoTimeout(Socket.java:1180)
        at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:143)
        at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:116)
        at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:186)
        at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:128)
        at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:289)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:232)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:465)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:411)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:248)
        at java.net.URL.openStream(URL.java:1072)
        at com.example.ma18uus.myapplication.weatherView$weatherTask.parseXML(weatherView.java:85)
        at com.example.ma18uus.myapplication.weatherView$weatherTask.doInBackground(weatherView.java:73)
        at com.example.ma18uus.myapplication.weatherView$weatherTask.doInBackground(weatherView.java:68)
        at android.os.AsyncTask$3.call(AsyncTask.java:378)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:919)
D/EGL_emulation: eglMakeCurrent: 0xe7fa9ac0: ver 3 0 (tinfo 0xe7fe50e0)

I am getting an error about permissions but I have already set the required permissions on the manifest file, so I do not understand what I am doing wrong or what I have to fix, can someone shed any light on the situation?

Also, I am getting some errors about the doinbackground that I do not understand as well, is it because of the permission error that I get an error there as well or am I doing something wrong?

Edit#1:

Seems like i fixed the issue with permissions from the link you gave me but now it looks like i have Fatal exception in my doinbackground in my weatherview class.

Edit#2: When i am using the manifest 1 i am getting the error output 1 which gives me a permissions error, but when i am using manifest 2 which gets rid of the permissions error i am getting a tag error :/

Edit#3: Updated the error output and manifest file to match the current file, output

Thanks in advance!!

  • Check this https://stackoverflow.com/questions/51902629/how-to-allow-all-network-connection-types-http-and-https-in-android-9-pie – Anas Mehar Jan 24 '20 at 11:56
  • You probably forgot to ask user for a permission to be granted to your app – Steyrix Jan 24 '20 at 11:57

2 Answers2

1

put this attribute in the manifest of application tag

android:usesCleartextTraffic="true"
Solanki Zeel
  • 548
  • 1
  • 7
  • 18
1

The tag name network_security_config rename it to network-security-config

Edit 1: Change it to this: <?xml version="1.0" encoding="utf-8"?> <network-security-config> <domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="true">www.weatherapi.com</domain> </domain-config> </network-security-config>

Edit 2: For the 2nd error output, It's telling you that you're using (with underscore) instead of (with dash), please make sure they are all dashes in the start and end tags.

ahmed galal
  • 504
  • 5
  • 15
  • 1
    This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/25178839) – leopal Jan 24 '20 at 13:20
  • If i change the name from network_security_config to network-security-config i get an error saying that the "-" is not a valid resource – dkkoronakis Jan 24 '20 at 13:25
  • Thanks @leopal , 'Unexpected start tag: found network_security_config, expected network-security-config' 'Caused by: java.lang.RuntimeException: Failed to parse XML configuration from network_security_config' These two lines indicate that he has typed the file name and tag name wrong as I assumed. – ahmed galal Jan 24 '20 at 13:26
  • In your edit you said the link in comments fixed the issue, I assume that you created the networkSecurityConfig file in your xml folder, right? Although, does the error happens on any android version or 9+? – ahmed galal Jan 24 '20 at 13:36
  • yes i created the networkSecurityConfig, the actual file is named network_security_config.xml and i am not sure if it happens only on 9+ – dkkoronakis Jan 24 '20 at 13:43
  • Can you please post the content of that file? After you followed the link, what fatal exception you have "in the question edit"? Also, make sure you put 'android:networkSecurityConfig="@xml/network_security_config"' in the Application tag in the Manifest. – ahmed galal Jan 24 '20 at 13:48
  • this is the file : ` ` – dkkoronakis Jan 24 '20 at 15:36
  • It worked and I got rid of the error, but now i am getting the 2nd error output i have on the main post – dkkoronakis Jan 24 '20 at 15:44
  • I updated the error output and the manifest file so they are both updated, also the network security config file is updated as well – dkkoronakis Jan 24 '20 at 16:18
  • Seems like it's working, there's no errors, just warnings ignore them. Everything is working properly? – ahmed galal Jan 24 '20 at 16:22
  • It looks like it is getting a socket error so the xml file i pull from the internet is not being shown – dkkoronakis Jan 24 '20 at 16:35
  • try to reinstall the app. – ahmed galal Jan 24 '20 at 16:39