how to retrieve WOEID from city name in android?

660 views Asked by At

I have madye a simple android demo in that i have put an editText and a butto ,I want is that when one enter anky city name and when one click on search button .A list of related WOEID should be listed,I have tried as below but its not working,It gives me an exception,My code is as below:

search.java

public class SesachActivity extends Activity {
    final String yahooapisBase = "http://query.yahooapis.com/v1/public/yql?q=select*from%20geo.places%20where%20text=";
    final String yahooapisFormat = "&format=xml";
    String yahooAPIsQuery;

    EditText place;
    Button search;
    ListView listviewWOEID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sesach);
        place = (EditText) findViewById(R.id.place);
        search = (Button) findViewById(R.id.search);
        listviewWOEID = (ListView) findViewById(R.id.woeidlist);

        search.setOnClickListener(searchOnClickListener);
    }

    Button.OnClickListener searchOnClickListener = new Button.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if (place.getText().toString().equals("")) {
                Toast.makeText(getBaseContext(), "Enter place!",
                        Toast.LENGTH_LONG).show();
            } else {
                ArrayList<String> l = QueryYahooAPIs();

                ArrayAdapter<String> aa = new ArrayAdapter<String>(
                        getBaseContext(), android.R.layout.simple_list_item_1,
                        l);

                listviewWOEID.setAdapter(aa);
            }
        }

    };

    private ArrayList<String> QueryYahooAPIs() {

        String uriPlace = Uri.encode(place.getText().toString());

        yahooAPIsQuery = yahooapisBase + "%22" + uriPlace + "%22"
                + yahooapisFormat;

        String woeidString = QueryYahooWeather(yahooAPIsQuery);
        Document woeidDoc = convertStringToDocument(woeidString);
        /*System.out.println(":::::::::::WOEID DOC::::::::::::"+woeid);*/
        return parseWOEID(woeidDoc);

    }

    private ArrayList<String> parseWOEID(Document srcDoc) {

        ArrayList<String> listWOEID = new ArrayList<String>();

        NodeList nodeListDescription = srcDoc.getElementsByTagName("woeid");
        if (nodeListDescription.getLength() >= 0) {
            for (int i = 0; i < nodeListDescription.getLength(); i++) {
                listWOEID.add(nodeListDescription.item(i).getTextContent());
            }
        } else {
            listWOEID.clear();
        }

        return listWOEID;
    }

    private Document convertStringToDocument(String src) {
        Document dest = null;

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder parser;

        try {
            parser = dbFactory.newDocumentBuilder();
            dest = parser.parse(new ByteArrayInputStream(src.getBytes()));
        } catch (ParserConfigurationException e1) {
            e1.printStackTrace();
            Toast.makeText(getBaseContext(), e1.toString(), Toast.LENGTH_LONG)
                    .show();
        } catch (SAXException e) {
            e.printStackTrace();
            Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
                    .show();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
                    .show();
        }

        return dest;

    }

    private String QueryYahooWeather(String queryString) {

        String qResult = "";

        HttpClient httpClient = new DefaultHttpClient();

        // return Uri.encode(queryString);

        HttpGet httpGet = new HttpGet(queryString);

        try {
            HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();

            if (httpEntity != null) {
                InputStream inputStream = httpEntity.getContent();
                Reader in = new InputStreamReader(inputStream);
                BufferedReader bufferedreader = new BufferedReader(in);
                StringBuilder stringBuilder = new StringBuilder();

                String stringReadLine = null;

                while ((stringReadLine = bufferedreader.readLine()) != null) {
                    stringBuilder.append(stringReadLine + "\n");
                }

                qResult = stringBuilder.toString();
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
            Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
                    .show();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
                    .show();
        }

        return qResult;

    }

}

Logcat

01-02 07:00:34.624: E/AndroidRuntime(1792): FATAL EXCEPTION: main
01-02 07:00:34.624: E/AndroidRuntime(1792): android.os.NetworkOnMainThreadException
01-02 07:00:34.624: E/AndroidRuntime(1792):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
01-02 07:00:34.624: E/AndroidRuntime(1792):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
01-02 07:00:34.624: E/AndroidRuntime(1792):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
01-02 07:00:34.624: E/AndroidRuntime(1792):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
01-02 07:00:34.624: E/AndroidRuntime(1792):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
01-02 07:00:34.624: E/AndroidRuntime(1792):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
01-02 07:00:34.624: E/AndroidRuntime(1792):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
01-02 07:00:34.624: E/AndroidRuntime(1792):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
01-02 07:00:34.624: E/AndroidRuntime(1792):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
01-02 07:00:34.624: E/AndroidRuntime(1792):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-02 07:00:34.624: E/AndroidRuntime(1792):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
01-02 07:00:34.624: E/AndroidRuntime(1792):     at com.example.dayweather.SesachActivity.QueryYahooWeather(SesachActivity.java:144)
01-02 07:00:34.624: E/AndroidRuntime(1792):     at com.example.dayweather.SesachActivity.QueryYahooAPIs(SesachActivity.java:81)
01-02 07:00:34.624: E/AndroidRuntime(1792):     at com.example.dayweather.SesachActivity.access$0(SesachActivity.java:74)
01-02 07:00:34.624: E/AndroidRuntime(1792):     at com.example.dayweather.SesachActivity$1.onClick(SesachActivity.java:62)
01-02 07:00:34.624: E/AndroidRuntime(1792):     at android.view.View.performClick(View.java:4240)
01-02 07:00:34.624: E/AndroidRuntime(1792):     at android.view.View$PerformClick.run(View.java:17721)
01-02 07:00:34.624: E/AndroidRuntime(1792):     at android.os.Handler.handleCallback(Handler.java:730)
01-02 07:00:34.624: E/AndroidRuntime(1792):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-02 07:00:34.624: E/AndroidRuntime(1792):     at android.os.Looper.loop(Looper.java:137)
01-02 07:00:34.624: E/AndroidRuntime(1792):     at android.app.ActivityThread.main(ActivityThread.java:5103)
01-02 07:00:34.624: E/AndroidRuntime(1792):     at java.lang.reflect.Method.invokeNative(Native Method)
01-02 07:00:34.624: E/AndroidRuntime(1792):     at java.lang.reflect.Method.invoke(Method.java:525)
01-02 07:00:34.624: E/AndroidRuntime(1792):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-02 07:00:34.624: E/AndroidRuntime(1792):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-02 07:00:34.624: E/AndroidRuntime(1792):     at dalvik.system.NativeStart.main(Native Method)

Please help me to solve it,Thank you in advance........!

1

There are 1 answers

0
FrancescoAzzola On

You are invoking an HTTP connection on the main Thread. You shouldn't do it because if the connection lags your app could be in ANR state and be terminated by the OS. You should move the Http connection stuff in another thread for example you could create a class that extends AsyncTask and in doBackground implement your logic. Hope this holp you.

PS: In my blog i made an example how to you it. If you are interested give a look here