Pages

Showing posts with label openweathermaps. Show all posts
Showing posts with label openweathermaps. Show all posts

Wednesday, April 27, 2016

Android query current weather using OpenWeatherMaps Weather API


OpenWeatherMaps weather API is simple, clear and free. This Android example show how access current weather data using OpenWeatherMaps weather API; for any location on Earth including over 200,000 cities! Current weather is frequently updated based on global models and data from more than 40,000 weather stations. Data is available in JSON, XML, or HTML format. This example use JSON.


To access the API you need to sign up for an API key, this example use the demo API Key (appid in the query)

MainActivity.java
package com.blogspot.android_er.androidopenweathermap;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class MainActivity extends AppCompatActivity {

EditText editTextCityName;
Button btnByCityName;
TextView textViewResult, textViewInfo;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextCityName = (EditText)findViewById(R.id.cityname);
btnByCityName = (Button)findViewById(R.id.bycityname);
textViewResult = (TextView)findViewById(R.id.result);
textViewInfo = (TextView)findViewById(R.id.info);

btnByCityName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new OpenWeatherMapTask(
editTextCityName.getText().toString(),
textViewResult).execute();
}
});
}

private class OpenWeatherMapTask extends AsyncTask<Void, Void, String> {

String cityName;
TextView tvResult;

String dummyAppid = "bd82977b86bf27fb59a04b61b657fb6f";
String queryWeather = "http://api.openweathermap.org/data/2.5/weather?q=";
String queryDummyKey = "&appid=" + dummyAppid;

OpenWeatherMapTask(String cityName, TextView tvResult){
this.cityName = cityName;
this.tvResult = tvResult;
}

@Override
protected String doInBackground(Void... params) {
String result = "";
String queryReturn;

String query = null;
try {
query = queryWeather + URLEncoder.encode(cityName, "UTF-8") + queryDummyKey;
queryReturn = sendQuery(query);
result += ParseJSON(queryReturn);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
queryReturn = e.getMessage();
} catch (IOException e) {
e.printStackTrace();
queryReturn = e.getMessage();
}


final String finalQueryReturn = query + " " + queryReturn;
runOnUiThread(new Runnable() {
@Override
public void run() {
textViewInfo.setText(finalQueryReturn);
}
});


return result;
}

@Override
protected void onPostExecute(String s) {
tvResult.setText(s);
}

private String sendQuery(String query) throws IOException {
String result = "";

URL searchURL = new URL(query);

HttpURLConnection httpURLConnection = (HttpURLConnection)searchURL.openConnection();
if(httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader,
8192);

String line = null;
while((line = bufferedReader.readLine()) != null){
result += line;
}

bufferedReader.close();
}

return result;
}

private String ParseJSON(String json){
String jsonResult = "";

try {
JSONObject JsonObject = new JSONObject(json);
String cod = jsonHelperGetString(JsonObject, "cod");

if(cod != null){
if(cod.equals("200")){

jsonResult += jsonHelperGetString(JsonObject, "name") + " ";
JSONObject sys = jsonHelperGetJSONObject(JsonObject, "sys");
if(sys != null){
jsonResult += jsonHelperGetString(sys, "country") + " ";
}
jsonResult += " ";

JSONObject coord = jsonHelperGetJSONObject(JsonObject, "coord");
if(coord != null){
String lon = jsonHelperGetString(coord, "lon");
String lat = jsonHelperGetString(coord, "lat");
jsonResult += "lon: " + lon + " ";
jsonResult += "lat: " + lat + " ";
}
jsonResult += " ";

JSONArray weather = jsonHelperGetJSONArray(JsonObject, "weather");
if(weather != null){
for(int i=0; i<weather.length(); i++){
JSONObject thisWeather = weather.getJSONObject(i);
jsonResult += "weather " + i + ": ";
jsonResult += "id: " + jsonHelperGetString(thisWeather, "id") + " ";
jsonResult += jsonHelperGetString(thisWeather, "main") + " ";
jsonResult += jsonHelperGetString(thisWeather, "description") + " ";
jsonResult += " ";
}
}

JSONObject main = jsonHelperGetJSONObject(JsonObject, "main");
if(main != null){
jsonResult += "temp: " + jsonHelperGetString(main, "temp") + " ";
jsonResult += "pressure: " + jsonHelperGetString(main, "pressure") + " ";
jsonResult += "humidity: " + jsonHelperGetString(main, "humidity") + " ";
jsonResult += "temp_min: " + jsonHelperGetString(main, "temp_min") + " ";
jsonResult += "temp_max: " + jsonHelperGetString(main, "temp_max") + " ";
jsonResult += "sea_level: " + jsonHelperGetString(main, "sea_level") + " ";
jsonResult += "grnd_level: " + jsonHelperGetString(main, "grnd_level") + " ";
jsonResult += " ";
}

jsonResult += "visibility: " + jsonHelperGetString(JsonObject, "visibility") + " ";
jsonResult += " ";

JSONObject wind = jsonHelperGetJSONObject(JsonObject, "wind");
if(wind != null){
jsonResult += "wind: ";
jsonResult += "speed: " + jsonHelperGetString(wind, "speed") + " ";
jsonResult += "deg: " + jsonHelperGetString(wind, "deg") + " ";
jsonResult += " ";
}

//...incompleted

}else if(cod.equals("404")){
String message = jsonHelperGetString(JsonObject, "message");
jsonResult += "cod 404: " + message;
}
}else{
jsonResult += "cod == null ";
}

} catch (JSONException e) {
e.printStackTrace();
jsonResult += e.getMessage();
}

return jsonResult;
}

private String jsonHelperGetString(JSONObject obj, String k){
String v = null;
try {
v = obj.getString(k);
} catch (JSONException e) {
e.printStackTrace();
}

return v;
}

private JSONObject jsonHelperGetJSONObject(JSONObject obj, String k){
JSONObject o = null;

try {
o = obj.getJSONObject(k);
} catch (JSONException e) {
e.printStackTrace();
}

return o;
}

private JSONArray jsonHelperGetJSONArray(JSONObject obj, String k){
JSONArray a = null;

try {
a = obj.getJSONArray(k);
} catch (JSONException e) {
e.printStackTrace();
}

return a;
}
}
}


layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout


android_layout_width="match_parent"
android_layout_height="match_parent"
android_padding="16dp"
android_orientation="vertical"
tools_context=".MainActivity">

<TextView
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_layout_gravity="center_horizontal"
android_autoLink="web"
android_text="http://android-er.blogspot.com/"
android_textStyle="bold" />

<EditText
android_id="@+id/cityname"
android_layout_width="match_parent"
android_layout_height="wrap_content"
android_hint="City name"/>
<Button
android_id="@+id/bycityname"
android_layout_width="match_parent"
android_layout_height="wrap_content"
android_text="Call current weather by city name"/>
<LinearLayout
android_layout_width="match_parent"
android_layout_height="match_parent"
android_orientation="horizontal">
<ScrollView
android_layout_width="0dp"
android_layout_height="match_parent"
android_layout_weight="1">
<TextView
android_id="@+id/result"
android_layout_width="match_parent"
android_layout_height="wrap_content"
android_textSize="20dp"
android_textStyle="bold"/>
</ScrollView>
<ScrollView
android_layout_width="0dp"
android_layout_height="match_parent"
android_layout_weight="1">
<TextView
android_id="@+id/info"
android_layout_width="match_parent"
android_layout_height="wrap_content"
android_textSize="18dp"
android_textStyle="italic"/>
</ScrollView>
</LinearLayout>

</LinearLayout>


Permission of "android.permission.INTERNET" is needed in AndroidManifest.xml.
 <uses-permission android_name="android.permission.INTERNET"/>


download filesDownload the files (Android Studio Format) .
Read More..

Wednesday, March 16, 2016

Mastering Android NDK

Master the skills you need to develop portable, highly-functional Android applications using NDK

Mastering Android NDK

About This Book
  • Develop portable games using Android NDK and debug them on your desktop
  • Familiarise yourself with different popular C++ libraries on Android and use them in your games
  • Write multi-threaded code with graphics, sound, networking, and resource storage
Who This Book Is For
If you want to leverage your C++ skills in mobile development and increase the performance of your Android applications, then this is the book for you. Knowledge of C or C++ is assumed, including pointer manipulation, multi-threading, object-oriented programming concepts, and the basics of C++11. It would be an added advantage if you know how to develop applications without any IDE.

What You Will Learn
  • Explore different popular C++ libraries and import some of them to Android
  • Write portable, multithreaded native code
  • Create applications that play audio with OpenAL
  • Implement gesture recognition in your games and applications
  • Debug mobile applications on your desktop
  • Extract resources from APK archives
  • Render text with FreeType and also use OpenGL ES
In Detail
Android NDK is used for multimedia applications that require direct access to system resources. NDK is also the key for portability, which in turn allows a reasonably comfortable development and debugging process using familiar tools such as GCC and Clang toolchains.

This is a hands-on guide to extending your game development skills with Android NDK. The book takes you through many clear, step-by-step example applications to help you further explore the features of Android NDK and some popular C++ libraries and boost your productivity by debugging the development process.

Through the course of this book, you will learn how to write portable multi-threaded native code, use HTTP networking in C++, play audio files, use OpenGL ES 3, and render high-quality text. Each chapter aims to take you one step closer to building your application. By the end of this book, you will be able to create an engaging, complete gaming application.

Style and approach
This book adopts a step-by-step approach and each chapter is based on the material from the previous ones. The book focuses on putting to your knowledge of C++ use while you develop Android applications of your own.

Read More..