Tashkent Weather ANDROID CLUB 2015.

Slides:



Advertisements
Similar presentations
Android course Database dr Milan Vidaković Chair of Informatics Faculty of Technical Sciences University of Novi Sad.
Advertisements

Cosc 4730 Android TabActivity and ListView. TabActivity A TabActivity allows for multiple “tabs”. – Each Tab is it’s own activity and the “root” activity.
Presenting Lists of Data. Lists of Data Issues involved – unknown number of elements – allowing the user to scroll Data sources – most common ArrayList.
Data Storage: Part 3 (SQLite)
Package org.androidtown.database.query; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase;
Mobile Programming Lecture 6
1 Announcements Homework #2 due Feb 7 at 1:30pm Submit the entire Eclipse project in Blackboard Please fill out the when2meets when your Project Manager.
로봇 전화번호부 4/4 UNIT 12 로봇 SW 콘텐츠 교육원 조용수. 학습 목표 뷰 홀더 패턴을 사용할 수 있다. 토스트를 사용할 수 있다. 클릭 이벤트를 처리할 수 있다. 2.
1/29/ Android Programming: FrameLayout By Dr. Ramji M. Makwana Professor and Head, Computer Engineering Department A.D. Patel.
ListView.
SQLite Android Club SQLite About onCreate Insert Select Update Delete onUpdate.
Create Navigation Drawer Team 2 Zhong Wang Jiaming Dong Philip Wu Lingduo Kong.
로봇 모니터링 1/2 UNIT 20 로봇 SW 콘텐츠 교육원 조용수. 학습 목표 Message Queue Handler 2.
1 Introducing Activity and Intent. 2 Memory LinearLayout, weight=2 LinearLayout, weight=1 TextView ListView.
Copyright© Jeffrey Jongko, Ateneo de Manila University Custom ListAdapters.
SQLite (part deux) 1 CS440. Traditional Model View Controller (MVC) CS440 2.
Mobile Software Development ISCG 7424 Department of Computing UNITEC John Casey and Richard Rabeder SQLite and Permissions.
HTTP ANDROID CLUB 2015.
ListView and ExpandableListView
SQlite. SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation.
Anekdot ANDROID CLUB Сегодня  Navigation Drawer  CardView  Calligraphy  TextToSpeech.
Android and s Ken Nguyen Clayton state University 2012.
Activity ANDROID CLUB Сегодня  Основные компоненты Android  Activity  Layout для Activity  Создание Activity  Launcher Activity  Activity.
Android Alert Dialog. Alert Dialog Place Button to open the dialog. public class MainActivity extends ActionBarActivity { private static Button button_sbm;
CMPE419 Mobile Application Development Asst.Prof.Dr.Ahmet Ünveren SPRING Computer Engineering Department Asst.Prof.Dr.Ahmet Ünveren
CMPE419 Mobile Application Development Asst.Prof.Dr.Ahmet Ünveren SPRING Computer Engineering Department Asst.Prof.Dr.Ahmet Ünveren
Lab7 – Appendix.
Lecture 3 Zablon Ochomo Android Layouts Lecture 3 Zablon Ochomo
Android Introduction Hello World
Android Layouts 8 May 2018 S.RENUKADEVI/AP/SCD/ANDROID LAYOUTS 1.
UNIT 11 로봇 전화번호부 3/4 로봇 SW 콘텐츠 교육원 조용수.
GUI Programming Fundamentals
Further android gui programming
ListView: Part 2.
CS499 – Mobile Application Development
Android Introduction Hello World.
Android Database using SQLite
Android Widgets 1 7 August 2018
Android Introduction Hello Views Part 1.
Android – Read/Write to External Storage
CIS 470 Mobile App Development
Android Programming Lecture 6
CIS 470 Mobile App Development
CIS 470 Mobile App Development
CIS 470 Mobile App Development
CIS 470 Mobile App Development
CIS 470 Mobile App Development
Android Sensor Programming
CIS 470 Mobile App Development
CA16R405 - Mobile Application Development (Theory)
CMPE419 Mobile Application Development
BMI Android Application will take weight and height from the users to calculate Body Mass Index (BMI) with the information, whether user is underweight,
Mobile Computing With Android ACST 4550 Android Database Storage
Activities and Intents
CIS 470 Mobile App Development
Android Developer Fundamentals V2
CIS 470 Mobile App Development
CIS 470 Mobile App Development
CIS 470 Mobile App Development
ListView A view that shows items in a vertically scrolling list. The items come from the ListAdapter associated with this view. ListAdapter is used to.
Adding Components to Activity
Korea Software HRD Center
CMPE419 Mobile Application Development
BLP 4216 MOBİL UYGULAMA GELİŞTİRME-2
Lasalle-App Tecnología Móvil.
Android Sensor Programming
Android Sensor Programming
CIS 694/EEC 693 Android Sensor Programming
CIS 694/EEC 693 Android Sensor Programming
CIS 694/EEC 693 Android Sensor Programming
Presentation transcript:

Tashkent Weather ANDROID CLUB 2015

Шаг 1: Daily Создавайте POJO – Daily. Содержит в себе: long time; String summary; String icon; double temperatureMin; double temperatureMax; Создавайте геттеры и сеттеры

Решение 1: public class Daily { long time; String summary; String icon; double temperatureMin; double temperatureMax; public long getTime() { return time; } public void setTime(long time) { this.time = time; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public double getTemperatureMin() { return temperatureMin; } public void setTemperatureMin(double temperatureMin) { this.temperatureMin = temperatureMin; } public double getTemperatureMax() { return temperatureMax; } public void setTemperatureMax(double temperatureMax) { this.temperatureMax = temperatureMax; } }

Шаг 2: БД Создавайте класс – MyDatabase. Наследник класса SQLiteOpenHelper Внутри класса создавайте объект класса SQLiteDatabase Конструктор принимает Context и вызывает конструктор класса родителя. Название БД – tw. Версия – 1 В конструкторе инициализируйте db В БД создавайте таблицу – daily. time – число, основной ключ summary – текст icon – текст temperatureMin – вещественное число temperatureMax – вещественное число

Решение 2: БД public class MyDatabase extends SQLiteOpenHelper{ SQLiteDatabase db; public MyDatabase(Context context) { super(context, "tw", null, 1); db = getWritableDatabase(); } @Override public void onCreate(SQLiteDatabase db) { String query = "CREATE TABLE daily(time INTEGER PRIMARY KEY, summary TEXT, icon TEXT, temperatureMin REAL, temperatureMax REAL)"; db.execSQL(query); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }

Шаг 3: Сохранить данные В классе MyDatabase, создавайте новый метод – saveDaily Принимает лист Daily – dailyList Сохраняет их в БД

Решение 3: Сохранить данные public void saveDaily(List<Daily> dailyList) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dailyList.size(); i++) { sb.append("INSERT OR REPLACE INTO daily(time, summary, icon, temperatureMin, temperatureMax) VALUES("); Daily daily = dailyList.get(i); sb.append(daily.getTime()); sb.append(",'"); sb.append(daily.getSummary()); sb.append("','"); sb.append(daily.getIcon()); sb.append("',"); sb.append(daily.getTemperatureMin()); sb.append(","); sb.append(daily.getTemperatureMax()); sb.append(");"); } String query = sb.toString(); db.execSQL(query); }

Шаг 4: Получить данные Создавайте новый метод – getDaily Ничего не принимает Возвращает лист Daily

Решение 4: public List<Daily> getDaily() { String query = "SELECT * FROM daily"; Cursor c = db.rawQuery(query, null); List<Daily> dailyList = new ArrayList<>(); while(c.moveToNext()) { Daily daily = new Daily(); daily.setTime(c.getLong(c.getColumnIndex("time"))); daily.setSummary(c.getString(c.getColumnIndex("summary"))); daily.setIcon(c.getString(c.getColumnIndex("icon"))); daily.setTemperatureMin(c.getDouble(c.getColumnIndex("temperatureMin"))); daily.setTemperatureMax(c.getDouble(c.getColumnIndex("temperatureMax"))); dailyList.add(daily); } return dailyList; }

Шаг 5: Загрузка данных Добавьте разрешение – android.permission.INTERNET Добавьте библиотеку - compile 'com.loopj.android:android-async-http:1.4.9' Создайте activity – LoadingActivity Получите данные из http://joerichard.net/api/tw/tw.json Получите лист Daily из json Сохраните лист в БД Переход в MainActivity

Решение 5: Загрузка данных public class LoadingActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_loading); AsyncHttpClient client = new AsyncHttpClient(); String url = "http://joerichard.net/api/tw/tw.json"; client.get(url, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { String json = new String(responseBody); List<Daily> dailyList = new ArrayList<Daily>(); try { JSONObject object = new JSONObject(json); JSONObject daily_json_object = object.getJSONObject("daily"); JSONArray data = daily_json_object.getJSONArray("data"); for (int i = 0; i < data.length(); i++) { JSONObject data_json_object = data.getJSONObject(i); Daily daily = new Daily(); daily.setTime(data_json_object.getLong("time")); daily.setSummary(data_json_object.getString("summary")); daily.setIcon(data_json_object.getString("icon")); daily.setTemperatureMin(data_json_object.getDouble("temperatureMin")); daily.setTemperatureMax(data_json_object.getDouble("temperatureMax")); dailyList.add(daily); } } catch (JSONException e) { e.printStackTrace(); } MyDatabase database = new MyDatabase(LoadingActivity.this); database.saveDaily(dailyList); Intent intent = new Intent(LoadingActivity.this, MainActivity.class); startActivity(intent); finish(); } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { } }); } }

Шаг 6: Layout Создавайте layout – listitem_daily. 4 TextView tvIcon tvWeekday tvSummary tvTemperature

Решение 6: Layout <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#E8644E"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="New Text" android:id="@+id/tvIcon" android:textColor="#FFFFFF" fontPath="fonts/climacons.ttf" tools:ignore="MissingPrefix" /> <LinearLayout android:orientation="vertical" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="New Text" android:id="@+id/tvWeekday" android:textColor="#FFFFFF"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="New Text" android:id="@+id/tvSummary" android:textColor="#FFFFFF"/> </LinearLayout> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="New Text" android:id="@+id/tvTemperature" android:textColor="#FFFFFF"/> </LinearLayout>

Шаг 7: Adapter Создавайте BaseAdapter – DailyListAdapter Принимает Сontext, лист Daily и инициализирует их Показывайте данные на listitem_daily

Решение 7: Adapter public class DailyListAdapter extends BaseAdapter{ Context context; List<Daily> dailyList; public DailyListAdapter(Context context, List<Daily> dailyList) { this.context = context; this.dailyList = dailyList; } @Override public int getCount() { return dailyList.size(); } @Override public Object getItem(int position) { return dailyList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { Daily daily = (Daily) getItem(position); View view = parent.inflate(context, R.layout.listitem_daily, null); TextView tvIcon = (TextView) view.findViewById(R.id.tvIcon); Typeface fontFamily = Typeface.createFromAsset(context.getAssets(), "fonts/climacons.ttf"); tvIcon.setTypeface(fontFamily); tvIcon.setText(icons.get(daily.getIcon())); // tvIcon.setText("\uE001"); // tvIcon.setText(context.getString(R.string.icon)); TextView tvWeekday = (TextView) view.findViewById(R.id.tvWeekday); tvWeekday.setText(String.valueOf(daily.getTime())); TextView tvSummary = (TextView) view.findViewById(R.id.tvSummary); tvSummary.setText(daily.getSummary()); TextView tvTemperature = (TextView) view.findViewById(R.id.tvTemperature); tvTemperature.setText(daily.getTemperatureMin()+"/"+daily.getT emperatureMax()); return view; }

Шаг 8: Иконки snow – 9 sleet – 0 wind – B fog – < cloudy – ! partly-cloudy-day – ” partly-cloudy-night – # hail – 3 thunderstorm – F tornado – X cloud-refresh – h Вставьте climacon.ttf в папку assets/fonts/ Создавайте HashMap – icons. Добавьте clear-day – I clear-night – N rain - $ Исползуя ключ показывайте иконку на tvIcon

Решение 8: Иконки HashMap<String, String> icons; public DailyListAdapter(Context context, List<Daily> dailyList) { this.context = context; this.dailyList = dailyList; icons = new HashMap<>(); icons.put("clear-day", "I"); icons.put("clear-night", "N"); icons.put("rain", "$"); icons.put("snow", "9"); icons.put("sleet", "0"); icons.put("wind", "B"); icons.put("fog", "<"); icons.put("cloudy", "!"); icons.put("partly-cloudy-day", "\""); icons.put("partly-cloudy-night", "#"); icons.put("hail", "3"); icons.put("thunderstorm", "F"); icons.put("tornado", "X"); icons.put("cloud-refresh", "h"); } TextView tvIcon = (TextView) view.findViewById(R.id.tvIcon); Typeface fontFamily = Typeface.createFromAsset(context.getAssets(), "fonts/climacons.ttf"); tvIcon.setTypeface(fontFamily); tvIcon.setText(icons.get(daily.getIcon()));

Шаг 9: Показывать данные Показывайте данные в MainActivity

Решение 9: Показывать данные public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MyDatabase database = new MyDatabase(MainActivity.this); List<Daily> dailyList = database.getDaily(); ListView lvDaily = (ListView) findViewById(R.id.lvDaily); DailyListAdapter adapter = new DailyListAdapter(MainActivity.this, dailyList); lvDaily.setAdapter(adapter); } }