神刀安全网

membuat aplikasi jadwal dan klasmen EURO 2016 android featuring api football-data

membuat aplikasi jadwal dan klasmen EURO 2016 android featuring api football-data

SideMenu

membuat aplikasi jadwal dan klasmen EURO 2016 android featuring api football-data

Jadwal Dan Hasil

Assalamualaikum wr.wb… Selamat siang, gimana nih gan puasanya pada lancar kan ?

alhamdullilah pada kesempatan kali ini ane akan memberi sedikit tutor di android studio yang berjudul “Membuat Aplikasi EURO 2016 Berbasis Android Dengan Android Studio” sebenarnya ni aplikasi sangat simple cuma bisa nampilkan klasmen, jadwal dan hasil pertandingan dan sebenarnya masih banyak API yang di sediakan oleh football-data.org.

alur apps sendiri pada awal opening aplikasi ane sengaja load dari local data JSONnya supaya lebih ringan. nah ketika di refresh maka dari restful-api akan update data ke database local (kebetulan memakai Realm-Android). so,, selamat bagi pendukung France yang menang 2-1 atas romania. membuat aplikasi jadwal dan klasmen EURO 2016 android featuring api football-data

Ok langsung saja …

1. Persiapan

Untuk persiapan pastikan agan sudah mempunyai tool2 berikut ini

a) JDK-8

b) SDK android

c) Android Studio

d) Api-key dari football-data (Free Restful tentang klasmen, jadwal dan hasil euro).

2. Library dan android manifest

a) build.gradel

apply plugin: 'com.android.application'  android {     compileSdkVersion 23     buildToolsVersion "23.0.2"     useLibrary 'org.apache.http.legacy'     defaultConfig {         applicationId "herudi.com.aplikasieuro"         minSdkVersion 15         targetSdkVersion 23         versionCode 1         versionName "1.0"     }     buildTypes {         release {             minifyEnabled false             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'         }     } }  dependencies {     compile fileTree(dir: 'libs', include: ['*.jar'])     testCompile 'junit:junit:4.12'     compile 'com.android.support:appcompat-v7:23.1.1'     compile 'com.android.support:design:23.1.1'     compile 'com.android.support:recyclerview-v7:23.1.1'     compile 'joda-time:joda-time:2.9.4' }  apply plugin: 'realm-android'

b) AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="herudi.com.aplikasieuro">     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>     <uses-permission android:name="android.permission.INTERNET"/>     <application         android:name=".app.MyApplication"         android:allowBackup="true"         android:icon="@mipmap/ic_bola_launcer"         android:label="@string/app_name"         android:supportsRtl="true"         android:theme="@style/AppTheme">         <activity             android:name=".MainActivity"             android:label="@string/app_name"             android:theme="@style/AppTheme.NoActionBar">             <intent-filter>                 <action android:name="android.intent.action.MAIN" />                 <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>         </activity>         <activity             android:name=".ActivityDetail"             android:label="@string/app_detail">             <meta-data                 android:name="android.support.PARENT_ACTIVITY"                 android:value=".MainActivity" />         </activity>         <activity             android:name=".ActivityAbout"             android:label="About Aplikasi">             <meta-data                 android:name="android.support.PARENT_ACTIVITY"                 android:value=".MainActivity" />         </activity>     </application>  </manifest>

3. Design

membuat aplikasi jadwal dan klasmen EURO 2016 android featuring api football-data

Klasmen Grup

membuat aplikasi jadwal dan klasmen EURO 2016 android featuring api football-data

Team Match

Jika semua sudah di persiapkan selanjutnya adalah memulai desainnya. kelebihan menggunakan android studio adalah bisa mendesain dengan drag n drop, dan itu akan membuat pengerjaan lebih cepat bila dibanding dengan phonegap seperti ionic dan lainnya yang cenderung hampir full di ketik.

A. Values

a) Colors.xml

<?xml version="1.0" encoding="utf-8"?> <resources>     <color name="colorPrimary">#3F51B5</color>     <color name="colorPrimaryDark">#303F9F</color>     <color name="colorAccent">#7986CB</color>     <color name="gray">#999999</color>     <color name="black">#222222</color>     <color name="red">#d21414</color>     <color name="green">#0fa412</color>     <color name="white">#ffffff</color> </resources>

b) Styles.xml

<resources>      <!-- Base application theme. -->     <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">         <item name="colorPrimary">@color/colorPrimary</item>         <item name="colorPrimaryDark">@color/colorPrimaryDark</item>         <item name="colorAccent">@color/colorAccent</item>     </style>      <style name="AppTheme.NoActionBar">         <item name="windowActionBar">false</item>         <item name="windowNoTitle">true</item>     </style>      <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />      <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" /> </resources>

c) Strings.xml

<resources>     <string name="app_name">EuroApps</string>      <string name="navigation_drawer_open">Open navigation drawer</string>     <string name="navigation_drawer_close">Close navigation drawer</string>      <string name="action_settings">Settings</string>     <string name="app_detail">Detail Team</string> </resources>

d) dimens.xml

<resources>     <dimen name="nav_header_vertical_spacing">16dp</dimen>     <dimen name="nav_header_height">160dp</dimen>     <dimen name="activity_horizontal_margin">16dp</dimen>     <dimen name="activity_vertical_margin">16dp</dimen>     <dimen name="fab_margin">16dp</dimen>     <dimen name="appbar_padding_top">8dp</dimen>     <dimen name="tab_padding_bottom">16dp</dimen>     <dimen name="tab_label">14sp</dimen>     <dimen name="custom_tab_layout_height">72dp</dimen> </resources>

B. Menu

a) activity_main_drawer.xml

<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto">      <group android:checkableBehavior="single">         <item             android:id="@+id/nav_table_league"             app:actionViewClass="android.widget.TextView"             android:icon="@drawable/table_league"             android:title="Klasmen Grup" />         <item             android:id="@+id/nav_match"             app:actionViewClass="android.widget.TextView"             android:icon="@drawable/football"             android:title="Jadwal & Hasil" />     </group>      <item android:title="Other">         <menu>             <item                 android:id="@+id/nav_about"                 android:icon="@drawable/info_about"                 android:title="About" />             <item                 android:id="@+id/nav_exit"                 android:icon="@drawable/shutdown"                 android:title="Exit" />         </menu>     </item>  </menu>

b) main.xml

<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto">     <item         android:id="@+id/action_about"         android:orderInCategory="100"         android:title="About Apps"         app:showAsAction="never"/>     <item         android:id="@+id/action_exit"         android:orderInCategory="100"         android:title="Exit"         app:showAsAction="never"/>     <!--<item android:id="@+id/action_search"-->         <!--android:icon="@drawable/ic_action_search"-->         <!--android:title="Search.."-->         <!--app:showAsAction="ifRoom"/>--> </menu>

C. Layout

a) main_activity.xml

<?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:id="@+id/drawer_layout"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:fitsSystemWindows="true"     tools:openDrawer="start">      <include         layout="@layout/app_bar_main"         android:layout_width="match_parent"         android:layout_height="match_parent" />      <android.support.design.widget.NavigationView         android:id="@+id/nav_view"         android:layout_width="wrap_content"         android:layout_height="match_parent"         android:layout_gravity="start"         android:fitsSystemWindows="true"         app:headerLayout="@layout/nav_header_main"         app:menu="@menu/activity_main_drawer"         android:background="@color/white"/>  </android.support.v4.widget.DrawerLayout>

b) app_bar_main.xml

<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:fitsSystemWindows="true"     tools:context="herudi.com.aplikasieuro.MainActivity">      <android.support.design.widget.AppBarLayout         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:theme="@style/AppTheme.AppBarOverlay">          <android.support.v7.widget.Toolbar             android:id="@+id/toolbar"             android:layout_width="match_parent"             android:layout_height="?attr/actionBarSize"             android:background="?attr/colorPrimary"             app:layout_scrollFlags="scroll|enterAlways"             app:popupTheme="@style/AppTheme.PopupOverlay" />     </android.support.design.widget.AppBarLayout>     <FrameLayout         android:id="@+id/frame"         android:layout_width="match_parent"         android:layout_height="match_parent"         android:layout_marginTop="?attr/actionBarSize"/>  </android.support.design.widget.CoordinatorLayout>

c) nav_header_main.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="@dimen/nav_header_height"     android:background="@drawable/nexus"     android:gravity="bottom"     android:orientation="vertical"     android:paddingBottom="@dimen/activity_vertical_margin"     android:paddingLeft="@dimen/activity_horizontal_margin"     android:paddingRight="@dimen/activity_horizontal_margin"     android:paddingTop="@dimen/activity_vertical_margin"     android:theme="@style/ThemeOverlay.AppCompat.Dark">      <ImageView         android:id="@+id/imageView"         android:layout_width="60dp"         android:layout_height="60dp"         android:paddingTop="@dimen/nav_header_vertical_spacing"         android:src="@drawable/bola" />      <TextView         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:paddingTop="@dimen/nav_header_vertical_spacing"         android:text="Euro Apps 2016"         android:textAppearance="@style/TextAppearance.AppCompat.Body1" />      <TextView         android:id="@+id/textView"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="Jadwal dan klasmen euro 2016" />  </LinearLayout>

d) fragment_klasmen.xml

<?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.SwipeRefreshLayout     xmlns:android="http://schemas.android.com/apk/res/android"     android:id="@+id/swipe_container"     android:layout_width="match_parent"     android:layout_height="match_parent">      <android.support.design.widget.CoordinatorLayout         android:layout_width="match_parent"         android:layout_height="match_parent"         android:layout_alignParentBottom="true"         android:layout_centerHorizontal="true"         android:id="@+id/snackbarPosition">         <LinearLayout             android:orientation="vertical"             android:layout_width="match_parent"             android:layout_height="match_parent"             android:weightSum="1">             <android.support.v7.widget.RecyclerView                 android:id="@+id/recycler_view"                 android:layout_width="match_parent"                 android:layout_height="wrap_content"                 android:scrollbars="vertical"                 android:background="@color/white"                 />          </LinearLayout>     </android.support.design.widget.CoordinatorLayout> </android.support.v4.widget.SwipeRefreshLayout>

e) tab_klasmen.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     android:orientation="vertical" android:layout_width="match_parent"     android:layout_height="match_parent">      <android.support.design.widget.TabLayout         android:id="@+id/tabs"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:background="@color/white"         app:tabMode="scrollable"         />      <android.support.v4.view.ViewPager         android:id="@+id/container"         android:layout_width="match_parent"         android:layout_height="match_parent"         app:layout_behavior="@string/appbar_scrolling_view_behavior" />  </LinearLayout>

f) klasmen_list_row.xml

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:focusable="true"     android:paddingLeft="16dp"     android:paddingRight="16dp"     android:paddingTop="10dp"     android:paddingBottom="10dp"     android:clickable="true"     android:background="?android:attr/selectableItemBackground"     android:orientation="vertical">       <TextView         android:id="@+id/teamName"         android:textColor="@color/colorPrimaryDark"         android:textSize="20dp"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_alignParentLeft="true"         android:layout_marginLeft="85dp" />     <TextView         android:id="@+id/teamPoints"         android:textColor="@color/red"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_alignParentTop="true"         android:layout_alignParentRight="true"         android:layout_below="@+id/teamName"         android:layout_marginRight="10dp"         android:layout_marginTop="20dp"         android:textSize="40dp" />     <TextView         android:id="@+id/teamPlayed"         android:textColor="@color/black"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_alignParentLeft="true"         android:layout_below="@+id/teamName"         android:layout_marginLeft="85dp" />     <TextView         android:id="@+id/teamGoal"         android:textColor="@color/black"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_alignParentLeft="true"         android:layout_below="@+id/teamName"         android:layout_marginLeft="155dp" />     <TextView         android:id="@+id/teamGoalsAgainst"         android:textColor="@color/black"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_alignParentLeft="true"         android:layout_below="@+id/teamGoal"         android:layout_marginLeft="85dp" />     <TextView         android:id="@+id/teamGoalDifference"         android:textColor="@color/black"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_alignParentLeft="true"         android:layout_below="@+id/teamGoal"         android:layout_marginLeft="155dp" />     <TextView         android:id="@+id/teamRank"         android:textColor="@color/black"         android:layout_width="wrap_content"         android:textStyle="bold"         android:layout_height="wrap_content"         android:layout_alignParentLeft="true"         android:layout_below="@+id/teamImage"/>     <ImageView         android:id="@+id/teamImage"         android:layout_width="50dp"         android:layout_height="50dp"/> </RelativeLayout>

g) fragment_matches.xml

<?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.SwipeRefreshLayout     xmlns:android="http://schemas.android.com/apk/res/android"     android:id="@+id/swipe_container"     android:layout_width="match_parent"     android:layout_height="match_parent">      <android.support.design.widget.CoordinatorLayout         android:layout_width="match_parent"         android:layout_height="match_parent"         android:layout_alignParentBottom="true"         android:layout_centerHorizontal="true"         android:id="@+id/snackbarPosition">         <LinearLayout             android:orientation="vertical"             android:layout_width="match_parent"             android:layout_height="match_parent"             android:weightSum="1">             <android.support.v7.widget.RecyclerView                 android:id="@+id/recycler_view"                 android:layout_width="match_parent"                 android:layout_height="wrap_content"                 android:scrollbars="vertical"                 android:background="@color/white"                 />          </LinearLayout>     </android.support.design.widget.CoordinatorLayout> </android.support.v4.widget.SwipeRefreshLayout>

h) tab_matches.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"     android:orientation="vertical" android:layout_width="match_parent"     android:layout_height="match_parent">      <android.support.design.widget.TabLayout         android:id="@+id/tabs"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:background="@color/white"         />      <android.support.v4.view.ViewPager         android:id="@+id/container"         android:layout_width="match_parent"         android:layout_height="match_parent"         app:layout_behavior="@string/appbar_scrolling_view_behavior" />  </LinearLayout>

i) match_list_row.xml

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:focusable="true"     android:paddingLeft="16dp"     android:paddingRight="16dp"     android:paddingTop="10dp"     android:paddingBottom="10dp"     android:clickable="true"     android:background="?android:attr/selectableItemBackground"     android:orientation="vertical">      <TextView         android:id="@+id/date"         android:textColor="@color/colorPrimary"         android:textSize="16dp"         android:gravity="center"         android:textStyle="bold"         android:layout_alignParentTop="true"         android:layout_width="match_parent"         android:layout_height="wrap_content" />     <ImageView         android:id="@+id/homeImage"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:adjustViewBounds="true"         android:layout_below="@+id/homeText"         android:maxWidth="40dp"         android:maxHeight="40dp"         android:minWidth="40dp"         android:minHeight="40dp"         android:layout_marginTop="15dp"/>     <TextView         android:id="@+id/homeText"         android:textColor="@color/black"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_below="@+id/date"         android:layout_alignParentLeft="true"/>     <TextView         android:id="@+id/versus"         android:textColor="@color/black"         android:gravity="center"         android:layout_below="@+id/date"         android:layout_width="match_parent"         android:layout_height="wrap_content"/>     <TextView         android:id="@+id/time"         android:textColor="@color/black"         android:gravity="center"         android:layout_below="@+id/versus"         android:layout_width="match_parent"         android:layout_height="wrap_content" />     <TextView         android:id="@+id/status"         android:textColor="@color/black"         android:gravity="center"         android:layout_below="@+id/time"         android:layout_width="match_parent"         android:layout_height="wrap_content" />     <TextView         android:id="@+id/homeScore"         android:textColor="@color/red"         android:textSize="39dp"         android:layout_below="@+id/homeText"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_alignParentLeft="true"         android:layout_marginLeft="50dp" />     <TextView         android:id="@+id/awayScore"         android:textColor="@color/red"         android:textSize="39dp"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_below="@+id/awayText"         android:layout_alignParentRight="true"         android:layout_marginRight="50dp" />     <ImageView         android:id="@+id/awayImage"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:adjustViewBounds="true"         android:layout_below="@+id/awayText"         android:maxWidth="40dp"         android:maxHeight="40dp"         android:minWidth="40dp"         android:minHeight="40dp"         android:layout_marginTop="15dp"         android:layout_alignParentRight="true" />     <TextView         android:id="@+id/awayText"         android:textColor="@color/black"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_below="@+id/date"         android:layout_alignParentRight="true"/> </RelativeLayout>

4. Coding Java

A. App

a) MyApplication.java

package herudi.com.aplikasieuro.app;  import android.app.Application; import android.os.AsyncTask; import android.util.Log;  import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;  import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date;  import herudi.com.aplikasieuro.models.Klasmens; import herudi.com.aplikasieuro.models.Matches; import io.realm.DynamicRealm; import io.realm.Realm; import io.realm.RealmConfiguration; import io.realm.RealmMigration; import io.realm.RealmResults; import io.realm.RealmSchema;  /**  * Created by herudi-sahimar on 06/06/2016.  */ public class MyApplication extends Application {     JSONArray dataJson = null;     private static final String TAG_OBJ = "fixtures";     private Realm realm;      @Override     public void onCreate() {         super.onCreate();         RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)                 .name("herudi.realm")                 .schemaVersion(2)                 .migration(new MyMigration())                 .build();         Realm.setDefaultConfiguration(realmConfiguration);         realm = Realm.getDefaultInstance();         RealmResults<Matches> result = realm.where(Matches.class).findAll();         if (result.size() == 0) {             new HelperMatches().execute();         } //        helperDelete();     }        private class HelperMatches extends AsyncTask<String, String, JSONObject> {          @Override         protected void onPreExecute() {             super.onPreExecute();         }          @Override         protected JSONObject doInBackground(String... args) {             JSONObject json = loadJSONFromAsset("matches.json");             return json;         }          @Override         protected void onPostExecute(JSONObject json) {             try {                 dataJson = json.getJSONArray(TAG_OBJ);                 for (int i = 0; i < dataJson.length(); i++) {                     JSONObject c = dataJson.getJSONObject(i);                     realm.beginTransaction();                     Matches m = realm.createObject(Matches.class);                     m.setMatch(c.getString("matchday"));                     m.setHomeText(c.getString("homeTeamName"));                     m.setAwayText(c.getString("awayTeamName"));                     String s = c.getString("date");                     String[] parts = s.split("T");                     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-dd");                     String dateInString = parts[0];                     Date date = sdf.parse(dateInString);                     SimpleDateFormat formatDate = new SimpleDateFormat("EEEE, d MMMM yyyy");                     String tanggal = formatDate.format(date);                     m.setDate(String.valueOf(tanggal));                     m.setVersus("VS");                     String strHomeFlag = "drawable/" + c.getString("homeTeamName").substring(0, 4).toLowerCase();                     int homeFlag = getResources().getIdentifier(strHomeFlag, null, getPackageName());                     String strAwayFlag = "drawable/" + c.getString("awayTeamName").substring(0, 4).toLowerCase();                     int awayFlag = getResources().getIdentifier(strAwayFlag, null,getPackageName());                     m.setHomeImage(homeFlag);                     m.setAwayImage(awayFlag);                     DateTimeZone timeZone = DateTimeZone.forID("Asia/Jakarta");                     DateTime time = new DateTime(c.getString("date"), timeZone);                     DateTimeFormatter formatterTime = DateTimeFormat.forPattern("HH:mm");                     m.setTime(formatterTime.print(time) + " - RCTI");                     m.setHomeScore("0");                     m.setAwayScore("0");                     m.setStatus("TIMED");                     realm.commitTransaction();                 }             } catch (JSONException e) {             } catch (ParseException e) {                 e.printStackTrace();             }         }     }      public JSONObject loadJSONFromAsset(String data) {         try {             InputStream is = getAssets().open(data);             int size = is.available();             byte[] buffer = new byte[size];             is.read(buffer);             is.close();             String a = new String(buffer, "UTF-8");             JSONObject json = new JSONObject(a);             return json;         } catch (IOException ex) {             ex.printStackTrace();             return null;         } catch (JSONException e) {             e.printStackTrace();             return null;         }     }      private void helperDelete(){         Realm realm = Realm.getDefaultInstance();         RealmResults<Klasmens> results = realm.where(Klasmens.class).findAll();         RealmResults<Matches> results2 = realm.where(Matches.class).findAll();         realm.beginTransaction();         results.deleteAllFromRealm();         results2.deleteAllFromRealm();         realm.commitTransaction();         Log.d("Delete...","Sukses");     }      private void helperInsert(){      }      private class MyMigration implements RealmMigration {         @Override         public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {             RealmSchema schema = realm.getSchema();             if (oldVersion == 0) {                 schema.create("Matches")                         .addField("homeText", String.class)                         .addField("homeScore", String.class)                         .addField("versus", String.class)                         .addField("date", String.class)                         .addField("time", String.class)                         .addField("awayText", String.class)                         .addField("awayScore", String.class)                         .addField("match", String.class)                         .addField("status", String.class)                         .addField("homeImage", int.class)                         .addField("awayImage", int.class);                 schema.create("Klasmens")                         .addField("teamName", String.class)                         .addField("teamPlayed", String.class)                         .addField("tealGoal", String.class)                         .addField("teamGoalAga", String.class)                         .addField("teamGoalDif", String.class)                         .addField("teamRank", String.class)                         .addField("grup", String.class)                         .addField("teamImage", int.class)                         .addField("teamPoint", String.class);                 oldVersion++;             }         }     }  }

B. Main

a) main_activity.java

package herudi.com.aplikasieuro;  import android.content.Intent; import android.graphics.Typeface; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.view.MenuItemCompat; import android.view.Gravity; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import herudi.com.aplikasieuro.fragments.FragmentKlasmens; import herudi.com.aplikasieuro.fragments.FragmentMatches;   public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener,         FragmentMatches.OnFragmentInteractionListener,         FragmentKlasmens.OnFragmentInteractionListener {     TextView matches, tableLeague;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);         setSupportActionBar(toolbar);         getSupportActionBar().setTitle("Klasmen Grup");         if (savedInstanceState == null) {             Fragment fragment = null;             Class fragmentClass = null;             fragmentClass = FragmentKlasmens.class;             try {                 fragment = (Fragment) fragmentClass.newInstance();             } catch (Exception e) {                 e.printStackTrace();             }             FragmentManager fragmentManager = getSupportFragmentManager();             fragmentManager.beginTransaction().replace(R.id.frame, fragment).commit();         }          DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);         ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);         drawer.setDrawerListener(toggle);         toggle.syncState();         NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);         navigationView.setNavigationItemSelectedListener(this);         matches = (TextView) MenuItemCompat.getActionView(navigationView.getMenu().findItem(R.id.nav_match));         tableLeague = (TextView) MenuItemCompat.getActionView(navigationView.getMenu().findItem(R.id.nav_table_league));         initializeBadge();     }      @Override     public void onBackPressed() {         DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);         if (drawer.isDrawerOpen(GravityCompat.START)) {             drawer.closeDrawer(GravityCompat.START);         } else {             super.onBackPressed();         }     }      @Override     public boolean onCreateOptionsMenu(Menu menu) {         getMenuInflater().inflate(R.menu.main, menu);         return true;     }      @Override     public boolean onOptionsItemSelected(MenuItem item) {         int id = item.getItemId();         if (id == R.id.action_about) {             startActivity(new Intent(this, ActivityAbout.class));             return true;         } else if (id == R.id.action_exit) {             System.exit(0);             return true;         }         return super.onOptionsItemSelected(item);     }      @SuppressWarnings("StatementWithEmptyBody")     @Override     public boolean onNavigationItemSelected(MenuItem item) {         int id = item.getItemId();         Fragment fragment = null;         Class fragmentClass = null;         if (id == R.id.nav_table_league) {             getSupportActionBar().setTitle("Klasmen Grup");             fragmentClass = FragmentKlasmens.class;         }else if (id == R.id.nav_match) {             getSupportActionBar().setTitle("Jadwal & Hasil");             fragmentClass = FragmentMatches.class;         } else if (id == R.id.nav_about) {             startActivity(new Intent(this, ActivityAbout.class));             return true;         } else if (id == R.id.nav_exit) {             System.exit(0);         }         try {             fragment = (Fragment) fragmentClass.newInstance();         } catch (Exception e) {             e.printStackTrace();         }         FragmentManager fragmentManager = getSupportFragmentManager();         fragmentManager.beginTransaction().replace(R.id.frame, fragment).commit();         DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);         drawer.closeDrawer(GravityCompat.START);         return true;     }      @Override     public void onFragmentInteraction(Uri uri) {      }       private void initializeBadge() {         matches.setGravity(Gravity.CENTER_VERTICAL);         matches.setTypeface(null, Typeface.BOLD);         matches.setTextColor(getResources().getColor(R.color.red));         matches.setText("24");         tableLeague.setGravity(Gravity.CENTER_VERTICAL);         tableLeague.setTypeface(null, Typeface.BOLD);         tableLeague.setTextColor(getResources().getColor(R.color.red));         tableLeague.setText("36");     }   }

C. Utils

a) JSONParser.java

package herudi.com.aplikasieuro.utils;  import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import org.json.JSONException; import org.json.JSONObject;  import android.util.Log;  public class JSONParser {      static InputStream is = null;     static JSONObject jObj = null;     static String json = "";      public JSONParser() {      }      public JSONObject getJSONFromUrl(String url) {         BufferedReader reader = null;         try {             URL urlp = new URL(url);             try {                 HttpURLConnection c = (HttpURLConnection) urlp.openConnection();                 c.setRequestMethod("GET");                 c.setRequestProperty("X-Auth-Token", "your-api-here");                 c.setReadTimeout(10000);                 c.connect();                 reader = new BufferedReader(new InputStreamReader(c.getInputStream(), "UTF-8"));                 StringBuilder buf = new StringBuilder();                 String line = null;                 while ((line = reader.readLine()) != null) {                     buf.append(line);                 }                 json = buf.toString();             } finally {                 if (reader != null) {                     reader.close();                 }             }          } catch (IOException e) {             Log.e("Error", "Error " + e.toString());         }         try {             jObj = new JSONObject(json);         } catch (JSONException e) {             Log.e("JSON Parser", "Error parsing data " + e.toString());         }         return jObj;      } }

D. Models

a) Klasmens.java

package herudi.com.aplikasieuro.models;  import io.realm.RealmObject;  /**  * Created by herudi-sahimar on 05/06/2016.  */  public class Klasmens extends RealmObject {     private String teamName, teamPlayed, teamGoal, teamGoalAga, teamGoalDif, teamRank, grup, teamPoint;     private int teamImage;      public Klasmens() {     }      public String getTeamPlayed() {         return teamPlayed;     }      public void setTeamPlayed(String teamPlayed) {         this.teamPlayed = teamPlayed;     }      public String getTeamName() {         return teamName;     }      public void setTeamName(String teamName) {         this.teamName = teamName;     }      public String getTeamGoal() {         return teamGoal;     }      public void setTeamGoal(String teamGoal) {         this.teamGoal = teamGoal;     }      public String getTeamGoalAga() {         return teamGoalAga;     }      public void setTeamGoalAga(String teamGoalAga) {         this.teamGoalAga = teamGoalAga;     }      public String getTeamGoalDif() {         return teamGoalDif;     }      public void setTeamGoalDif(String teamGoalDif) {         this.teamGoalDif = teamGoalDif;     }      public String getTeamRank() {         return teamRank;     }      public void setTeamRank(String teamRank) {         this.teamRank = teamRank;     }      public int getTeamImage() {         return teamImage;     }      public void setTeamImage(int teamImage) {         this.teamImage = teamImage;     }      public String getGrup() {         return grup;     }      public void setGrup(String grup) {         this.grup = grup;     }      public String getTeamPoint() {         return teamPoint;     }      public void setTeamPoint(String teamPoint) {         this.teamPoint = teamPoint;     } }

b) Matches.java

package herudi.com.aplikasieuro.models;  import android.graphics.Bitmap; import android.graphics.drawable.Drawable;  import io.realm.RealmObject; import io.realm.annotations.PrimaryKey;  /**  * Created by herudi-sahimar on 04/06/2016.  */ public class Matches extends RealmObject {     private String             homeText,             homeScore,             versus,             date,             time,             awayText,             awayScore,             match,             status;     private int homeImage, awayImage;      public Matches() {     }      public String getMatch() {         return match;     }      public void setMatch(String match) {         this.match = match;     }      public String getHomeText() {         return homeText;     }      public void setHomeText(String homeText) {         this.homeText = homeText;     }      public String getHomeScore() {         return homeScore;     }      public void setHomeScore(String homeScore) {         this.homeScore = homeScore;     }      public String getVersus() {         return versus;     }      public void setVersus(String versus) {         this.versus = versus;     }      public String getDate() {         return date;     }      public void setDate(String date) {         this.date = date;     }      public String getTime() {         return time;     }      public void setTime(String time) {         this.time = time;     }      public String getAwayText() {         return awayText;     }      public void setAwayText(String awayText) {         this.awayText = awayText;     }      public String getAwayScore() {         return awayScore;     }      public void setAwayScore(String awayScore) {         this.awayScore = awayScore;     }      public int getHomeImage() {         return homeImage;     }      public void setHomeImage(int homeImage) {         this.homeImage = homeImage;     }      public int getAwayImage() {         return awayImage;     }      public void setAwayImage(int awayImage) {         this.awayImage = awayImage;     }      public String getStatus() {         return status;     }      public void setStatus(String status) {         this.status = status;     } }

E. Frames

a) FrameGrup.java

package herudi.com.aplikasieuro.frames;  import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.StrictMode; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup;  import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;  import herudi.com.aplikasieuro.ActivityDetail; import herudi.com.aplikasieuro.R; import herudi.com.aplikasieuro.helpers.HelperJson; import herudi.com.aplikasieuro.models.Klasmens; import herudi.com.aplikasieuro.utils.JSONParser; import herudi.com.aplikasieuro.utils.KlasmenAdapter; import herudi.com.aplikasieuro.utils.RecyclerItemClickListener; import herudi.com.aplikasieuro.utils.SimpleDividerItemDecoration; import io.realm.Realm; import io.realm.RealmList; import io.realm.RealmResults;   /**  * Created by herudi-sahimar on 04/06/2016.  */ public class FrameGrup extends Fragment {     private static String url = "http://api.football-data.org/v1/soccerseasons/424/leagueTable";     JSONArray dataJson = null;     private RealmList<Klasmens> listData = new RealmList<>();     private RecyclerView recyclerView;     private KlasmenAdapter mAdapter;     private SwipeRefreshLayout swipeRefreshLayout;     private Handler handler = new Handler();     View coordinatorLayoutView;     private Realm realm;     private String teamOfGrup;       public FrameGrup() {     }      @SuppressLint("ValidFragment")     public FrameGrup(String grup) {         teamOfGrup = grup;     }      public static FrameGrup newInstance(String a) {         FrameGrup fragment = new FrameGrup(a);         Bundle args = new Bundle();         fragment.setArguments(args);         return fragment;     }      @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);     }      @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {         View view = inflater.inflate(R.layout.fragment_klasmens, container, false);         recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);         swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);         mAdapter = new KlasmenAdapter(listData);         RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(view.getContext());         recyclerView.addItemDecoration(new SimpleDividerItemDecoration(getResources()));         recyclerView.setLayoutManager(mLayoutManager);         recyclerView.setItemAnimator(new DefaultItemAnimator());         recyclerView.setAdapter(mAdapter);         coordinatorLayoutView = view.findViewById(R.id.snackbarPosition);         swipeRefreshLayout.setColorSchemeResources(R.color.green, R.color.red, R.color.black);         realm = Realm.getDefaultInstance();         firstLoad();         swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {             @Override             public void onRefresh() {                 handler.post(refreshing);             }         });         recyclerView.addOnItemTouchListener(                 new RecyclerItemClickListener(getContext(), new RecyclerItemClickListener.OnItemClickListener() {                     @Override                     public void onItemClick(View view, int position) {                         ActivityDetail.team = listData.get(position).getTeamName();                         startActivity(new Intent(getActivity(), ActivityDetail.class));                     }                 })         );          return view;     }      private void findByGrup() {         listData.clear();         RealmResults<Klasmens> insert = realm.where(Klasmens.class).equalTo("grup", teamOfGrup).findAll();         listData.addAll(insert);         mAdapter.notifyDataSetChanged();         swipeRefreshLayout.setRefreshing(false);     }      private void firstLoad() {         RealmResults<Klasmens> result = realm.where(Klasmens.class).equalTo("grup", teamOfGrup).findAll();         if (result.size() == 0) {             new Helper().execute();         } else {             if (isNetworkAvaliable(getContext())) {                 findByGrup();             } else {                 findByGrup();                 Snackbar snackbar = Snackbar.make(coordinatorLayoutView, "No internet connection!", Snackbar.LENGTH_LONG);                 snackbar.show();             }          }     }      private void realodGrup() {         RealmResults<Klasmens> result = realm.where(Klasmens.class).equalTo("grup", teamOfGrup).findAll();         if (result.size() == 0) {             new Helper().execute();         } else {             if (isNetworkAvaliable(getContext())) {                 new updateData().execute();             } else {                 findByGrup();                 Snackbar snackbar = Snackbar.make(coordinatorLayoutView, "No internet connection!", Snackbar.LENGTH_LONG);                 snackbar.show();             }          }      }      private void getData() {         realodGrup();     }      private final Runnable refreshing = new Runnable() {         public void run() {             try {                 handler.postDelayed(new Runnable() {                     @Override                     public void run() {                         getData();                     }                 }, 1000);             } catch (Exception e) {                 e.printStackTrace();             }         }     };       private class Helper extends AsyncTask<String, String, JSONObject> {          @Override         protected void onPreExecute() {             super.onPreExecute();         }          @Override         protected JSONObject doInBackground(String... args) {             JSONObject json = HelperJson.loadJSONFromAsset(getActivity(), "grup.json");             return json;         }          @Override         protected void onPostExecute(JSONObject json) {             try {                 JSONObject standings = json.getJSONObject("standings");                 dataJson = standings.getJSONArray(teamOfGrup);                 for (int i = 0; i < dataJson.length(); i++) {                     JSONObject grup = dataJson.getJSONObject(i);                     realm.beginTransaction();                     Klasmens k = realm.createObject(Klasmens.class);                     k.setGrup(teamOfGrup);                     k.setTeamName(grup.getString("team"));                     k.setTeamPlayed("GP = " + grup.getString("playedGames"));                     k.setTeamGoal("G = " + grup.getString("goals"));                     k.setTeamGoalAga("GA = " + grup.getString("goalsAgainst"));                     k.setTeamGoalDif("GD = " + grup.getString("goalDifference"));                     k.setTeamRank("Rank = "+grup.getString("rank"));                     k.setTeamPoint(grup.getString("points"));                     String strImg = "drawable/" + grup.getString("team").substring(0, 4).toLowerCase();                     int img = getContext().getResources().getIdentifier(strImg, null, getContext().getPackageName());                     k.setTeamImage(img);                     realm.commitTransaction();                  }                 findByGrup();             } catch (JSONException e) {              }         }      }      private class updateData extends AsyncTask<String, String, JSONObject> {         @Override         protected void onPreExecute() {             super.onPreExecute();         }          @Override         protected JSONObject doInBackground(String... args) {             StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();             StrictMode.setThreadPolicy(policy);             JSONParser jParser = new JSONParser();             JSONObject json = jParser.getJSONFromUrl(url);             return json;         }          @Override         protected void onPostExecute(JSONObject json) {             try {                 JSONObject standings = json.getJSONObject("standings");                 RealmResults<Klasmens> update = realm.where(Klasmens.class).equalTo("grup", teamOfGrup).findAll();                 dataJson = standings.getJSONArray(teamOfGrup);                 if (update.size() == dataJson.length()) {                     for (int i = 0; i < dataJson.length(); i++) {                         JSONObject grup = dataJson.getJSONObject(i);                         realm.beginTransaction();                         Klasmens k = update.get(i);                         k.setGrup(teamOfGrup);                         k.setTeamName(grup.getString("team"));                         k.setTeamPlayed("GP = " + grup.getString("playedGames"));                         k.setTeamGoal("G = " + grup.getString("goals"));                         k.setTeamGoalAga("GA = " + grup.getString("goalsAgainst"));                         k.setTeamGoalDif("GD = " + grup.getString("goalDifference"));                         k.setTeamRank("Rank = "+grup.getString("rank"));                         k.setTeamPoint(grup.getString("points"));                         String strImg = "drawable/" + grup.getString("team").substring(0, 4).toLowerCase();                         int img = getContext().getResources().getIdentifier(strImg, null, getContext().getPackageName());                         k.setTeamImage(img);                         realm.commitTransaction();                      }                     findByGrup();                 }              } catch (JSONException e) {              }         }      }       public boolean isNetworkAvaliable(Context ctx) {         ConnectivityManager connectivityManager = (ConnectivityManager) ctx                 .getSystemService(Context.CONNECTIVITY_SERVICE);         if ((connectivityManager                 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null && connectivityManager                 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED)                 || (connectivityManager                 .getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null && connectivityManager                 .getNetworkInfo(ConnectivityManager.TYPE_WIFI)                 .getState() == NetworkInfo.State.CONNECTED)) {             return true;         } else {             return false;         }     }  }

b) FrameMatch.java

package herudi.com.aplikasieuro.frames;  import android.annotation.SuppressLint; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.StrictMode; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup;  import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;  import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date;  import herudi.com.aplikasieuro.R; import herudi.com.aplikasieuro.helpers.HelperJson; import herudi.com.aplikasieuro.models.Matches; import herudi.com.aplikasieuro.utils.JSONParser; import herudi.com.aplikasieuro.utils.MatchAdapter; import herudi.com.aplikasieuro.utils.SimpleDividerItemDecoration; import io.realm.Realm; import io.realm.RealmList; import io.realm.RealmResults;   /**  * Created by herudi-sahimar on 04/06/2016.  */ public class FrameMatch extends Fragment {     private static String url = "http://api.football-data.org/v1/soccerseasons/424/fixtures";     private static final String TAG_OBJ = "fixtures";     JSONArray dataJson = null;     private RealmList<Matches> matchList = new RealmList<>();     private RecyclerView recyclerView;     private MatchAdapter mAdapter;     private SwipeRefreshLayout swipeRefreshLayout;     private Handler handler = new Handler();     View coordinatorLayoutView;     private Realm realm;     private String match;      public FrameMatch() {     }      @SuppressLint("ValidFragment")     public FrameMatch(String asd) {         match = asd;     }      public static FrameMatch newInstance(String _match) {         FrameMatch fragment = new FrameMatch(_match);         Bundle args = new Bundle();         fragment.setArguments(args);         return fragment;     }      @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);     }      @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {         View view = inflater.inflate(R.layout.fragment_matches, container, false);         recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);         swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);         mAdapter = new MatchAdapter(matchList);         RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(view.getContext());         recyclerView.addItemDecoration(new SimpleDividerItemDecoration(getResources()));         recyclerView.setLayoutManager(mLayoutManager);         recyclerView.setItemAnimator(new DefaultItemAnimator());         recyclerView.setAdapter(mAdapter);         coordinatorLayoutView = view.findViewById(R.id.snackbarPosition);         swipeRefreshLayout.setColorSchemeResources(R.color.green, R.color.red, R.color.black);         realm = Realm.getDefaultInstance();         firstLoad();         swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {             @Override             public void onRefresh() {                 handler.post(refreshing);             }         });         return view;     }      private void getData() {         realodMatch();     }      private final Runnable refreshing = new Runnable() {         public void run() {             try {                 handler.postDelayed(new Runnable() {                     @Override                     public void run() {                         getData();                     }                 }, 1000);             } catch (Exception e) {                 e.printStackTrace();             }         }     };      private class Helper extends AsyncTask<String, String, JSONObject> {          @Override         protected void onPreExecute() {             super.onPreExecute();         }          @Override         protected JSONObject doInBackground(String... args) {             JSONObject json = HelperJson.loadJSONFromAsset(getActivity(), "match" + match + ".json");             return json;         }          @Override         protected void onPostExecute(JSONObject json) {             try {                 dataJson = json.getJSONArray(TAG_OBJ);                 for (int i = 0; i < dataJson.length(); i++) {                     JSONObject c = dataJson.getJSONObject(i);                     JSONObject result = c.getJSONObject("result");                     realm.beginTransaction();                     Matches m = realm.createObject(Matches.class);                     m.setMatch(c.getString("matchday"));                     m.setHomeText(c.getString("homeTeamName"));                     m.setAwayText(c.getString("awayTeamName"));                     String s = c.getString("date");                     String[] parts = s.split("T");                     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-dd");                     String dateInString = parts[0];                     Date date = sdf.parse(dateInString);                     SimpleDateFormat formatDate = new SimpleDateFormat("EEEE, d MMMM yyyy");                     String tanggal = formatDate.format(date);                     m.setDate(String.valueOf(tanggal));                     m.setVersus("VS");                     String strHomeFlag = "drawable/" + c.getString("homeTeamName").substring(0, 4).toLowerCase();                     int homeFlag = getContext().getResources().getIdentifier(strHomeFlag, null, getContext().getPackageName());                     String strAwayFlag = "drawable/" + c.getString("awayTeamName").substring(0, 4).toLowerCase();                     int awayFlag = getContext().getResources().getIdentifier(strAwayFlag, null, getContext().getPackageName());                     m.setHomeImage(homeFlag);                     m.setAwayImage(awayFlag);                     DateTimeZone timeZone = DateTimeZone.forID("Asia/Jakarta");                     DateTime time = new DateTime(c.getString("date"), timeZone);                     DateTimeFormatter formatterTime = DateTimeFormat.forPattern("HH:mm");                     m.setTime(formatterTime.print(time) + " - RCTI");                     if (result.getString("goalsHomeTeam").equals("null")) {                         m.setHomeScore("0");                     } else {                         m.setHomeScore(result.getString("goalsHomeTeam"));                     }                     if (result.getString("goalsAwayTeam").equals("null")) {                         m.setAwayScore("0");                     } else {                         m.setAwayScore(result.getString("goalsAwayTeam"));                     }                     if (c.getString("status").equals("TIMED")) {                         m.setStatus("TIMED");                     }else if(c.getString("status").equals("FINISHED")){                         m.setStatus("FULLTIME");                     }else{                         m.setStatus("IN_PLAY");                     }                     realm.commitTransaction();                 }                 findByMatch();             } catch (JSONException e) {             } catch (ParseException e) {                 e.printStackTrace();             }         }     }       private void findByMatch() {         matchList.clear();         RealmResults<Matches> insert = realm.where(Matches.class).equalTo("match", match).findAll();         matchList.addAll(insert);         mAdapter.notifyDataSetChanged();         swipeRefreshLayout.setRefreshing(false);     }      private void firstLoad(){         //Jika Tidak Meload helpermatches dari myapplication //        RealmResults<Matches> result = realm.where(Matches.class).equalTo("match", match).findAll(); //        if (result.size() == 0) { //            new Helper().execute(); //        } else { //            if (isNetworkAvaliable(getContext())) { //                findByMatch(); //            } else { //                findByMatch(); //                Snackbar snackbar = Snackbar.make(coordinatorLayoutView, "No internet connection!", Snackbar.LENGTH_LONG); //                snackbar.show(); //            } //        }         if (isNetworkAvaliable(getContext())) {             findByMatch();         } else {             findByMatch();             Snackbar snackbar = Snackbar.make(coordinatorLayoutView, "No internet connection!", Snackbar.LENGTH_LONG);             snackbar.show();         }     }      private void realodMatch() {         //Jika Tidak Meload helpermatches dari myapplication //        RealmResults<Matches> result = realm.where(Matches.class).equalTo("match", match).findAll(); //        if (result.size() == 0) { //            new Helper().execute(); //        } else { //            if (isNetworkAvaliable(getContext())) { //                new updateData().execute(); //            } else { //                findByMatch(); //                Snackbar snackbar = Snackbar.make(coordinatorLayoutView, "No internet connection!", Snackbar.LENGTH_LONG); //                snackbar.show(); //            } // //        }         if (isNetworkAvaliable(getContext())) {             new updateData().execute();         } else {             findByMatch();             Snackbar snackbar = Snackbar.make(coordinatorLayoutView, "No internet connection!", Snackbar.LENGTH_LONG);             snackbar.show();         }      }      public class updateData extends AsyncTask<String, String, JSONObject> {         @Override         protected void onPreExecute() {             super.onPreExecute();         }          @Override         protected JSONObject doInBackground(String... args) {             StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();             StrictMode.setThreadPolicy(policy);             JSONParser jParser = new JSONParser();             JSONObject json = jParser.getJSONFromUrl("http://api.football-data.org/v1/soccerseasons/424/fixtures?matchday=" + match);             return json;         }          @Override         protected void onPostExecute(JSONObject json) {             try {                 RealmResults<Matches> update = realm.where(Matches.class).equalTo("match", match).findAll();                 dataJson = json.getJSONArray(TAG_OBJ); //                Log.d("update : ",String.valueOf(update.size())); //                Log.d("json : ",String.valueOf(dataJson.length()));                 if (update.size() == dataJson.length()) {                     for (int i = 0; i < dataJson.length(); i++) {                         JSONObject c = dataJson.getJSONObject(i);                         JSONObject result = c.getJSONObject("result");                         realm.beginTransaction();                         Matches m = update.get(i);                         String s = c.getString("date");                         String[] parts = s.split("T");                         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-dd");                         String dateInString = parts[0];                         Date date = sdf.parse(dateInString);                         SimpleDateFormat formatDate = new SimpleDateFormat("EEEE, d MMMM yyyy");                         String tanggal = formatDate.format(date);                         m.setDate(String.valueOf(tanggal));                         DateTimeZone timeZone = DateTimeZone.forID("Asia/Jakarta");                         DateTime time = new DateTime(c.getString("date"), timeZone);                         DateTimeFormatter formatterTime = DateTimeFormat.forPattern("HH:mm");                         m.setTime(formatterTime.print(time) + " - RCTI");                         if (result.getString("goalsHomeTeam").equals("null")) {                             m.setHomeScore("0");                         } else {                             m.setHomeScore(result.getString("goalsHomeTeam"));                         }                         if (result.getString("goalsAwayTeam").equals("null")) {                             m.setAwayScore("0");                         } else {                             m.setAwayScore(result.getString("goalsAwayTeam"));                         }                         if (c.getString("status").equals("TIMED")) {                             m.setStatus("TIMED");                         }else if(c.getString("status").equals("FINISHED")){                             m.setStatus("FULLTIME");                         }else{                             m.setStatus("IN_PLAY");                         }                         realm.commitTransaction();                      }                     findByMatch();                 }              } catch (JSONException e) {             } catch (ParseException e) {                 e.printStackTrace();             }         }      }       public boolean isNetworkAvaliable(Context ctx) {         ConnectivityManager connectivityManager = (ConnectivityManager) ctx                 .getSystemService(Context.CONNECTIVITY_SERVICE);         if ((connectivityManager                 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null && connectivityManager                 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED)                 || (connectivityManager                 .getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null && connectivityManager                 .getNetworkInfo(ConnectivityManager.TYPE_WIFI)                 .getState() == NetworkInfo.State.CONNECTED)) {             return true;         } else {             return false;         }     }  }

F. Fragments

a) FragmentKlasmens.java

package herudi.com.aplikasieuro.fragments;  import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup;  import java.util.ArrayList; import java.util.List;  import herudi.com.aplikasieuro.R; import herudi.com.aplikasieuro.frames.FrameGrup;   /**  * Created by herudi-sahimar on 04/06/2016.  */ public class FragmentKlasmens extends Fragment{      private OnFragmentInteractionListener mListener;     private ViewPager mViewPager;      @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);     }      @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {         View view = inflater.inflate(R.layout.tab_klasmen, container, false);         mViewPager = (ViewPager) view.findViewById(R.id.container);         setupViewPager(mViewPager);         TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabs);         tabLayout.setupWithViewPager(mViewPager);         return view;     }      private void setupViewPager(ViewPager viewPager) {         SectionsPagerAdapter adapter = new SectionsPagerAdapter(this.getChildFragmentManager());         adapter.addFragment(new FrameGrup("A"), "Grup A");         adapter.addFragment(new FrameGrup("B"), "Grup B");         adapter.addFragment(new FrameGrup("C"), "Grup C");         adapter.addFragment(new FrameGrup("D"), "Grup D");         adapter.addFragment(new FrameGrup("E"), "Grup E");         adapter.addFragment(new FrameGrup("F"), "Grup F");         viewPager.setAdapter(adapter);      }      public class SectionsPagerAdapter extends FragmentPagerAdapter {         public SectionsPagerAdapter(FragmentManager fm) {             super(fm);         }         private final List<Fragment> mFragmentList = new ArrayList<>();         private final List<String> mFragmentTitleList = new ArrayList<>();          @Override         public Fragment getItem(int position) {             return mFragmentList.get(position);         }          @Override         public int getCount() {             return mFragmentList.size();         }          public void addFragment(Fragment fragment, String title) {             mFragmentList.add(fragment);             mFragmentTitleList.add(title);         }          @Override         public CharSequence getPageTitle(int position) {             return mFragmentTitleList.get(position);         }     }      public void onButtonPressed(Uri uri) {         if (mListener != null) {             mListener.onFragmentInteraction(uri);         }     }      @Override     public void onAttach(Context context) {         super.onAttach(context);         if (context instanceof OnFragmentInteractionListener) {             mListener = (OnFragmentInteractionListener) context;         } else {             throw new RuntimeException(context.toString()                     + " must implement OnFragmentInteractionListener");         }     }      @Override     public void onDetach() {         super.onDetach();         mListener = null;     }      /**      * This interface must be implemented by activities that contain this      * fragment to allow an interaction in this fragment to be communicated      * to the activity and potentially other fragments contained in that      * activity.      * <p/>      * See the Android Training lesson <a href=      * "http://developer.android.com/training/basics/fragments/communicating.html"      * >Communicating with Other Fragments</a> for more information.      */     public interface OnFragmentInteractionListener {         void onFragmentInteraction(Uri uri);     } }

b) FragmentMatch.java

package herudi.com.aplikasieuro.fragments;  import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup;  import java.util.ArrayList; import java.util.List;  import herudi.com.aplikasieuro.R; import herudi.com.aplikasieuro.frames.FrameMatch;   /**  * Created by herudi-sahimar on 04/06/2016.  */ public class FragmentMatches extends Fragment{      private OnFragmentInteractionListener mListener;     private ViewPager mViewPager;      @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);     }      @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {         View view = inflater.inflate(R.layout.tab_matches, container, false);         mViewPager = (ViewPager) view.findViewById(R.id.container);         setupViewPager(mViewPager);         TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabs);         tabLayout.setupWithViewPager(mViewPager);         return view;     }      private void setupViewPager(ViewPager viewPager) {         SectionsPagerAdapter adapter = new SectionsPagerAdapter(this.getChildFragmentManager());         adapter.addFragment(new FrameMatch("1"), "Match 1");         adapter.addFragment(new FrameMatch("2"), "Match 2");         adapter.addFragment(new FrameMatch("3"), "Match 3");         viewPager.setAdapter(adapter);     }      public class SectionsPagerAdapter extends FragmentPagerAdapter {         public SectionsPagerAdapter(FragmentManager fm) {             super(fm);         }         private final List<Fragment> mFragmentList = new ArrayList<>();         private final List<String> mFragmentTitleList = new ArrayList<>();          @Override         public Fragment getItem(int position) {             return mFragmentList.get(position);         }          @Override         public int getCount() {             return mFragmentList.size();         }          public void addFragment(Fragment fragment, String title) {             mFragmentList.add(fragment);             mFragmentTitleList.add(title);         }          @Override         public CharSequence getPageTitle(int position) {             return mFragmentTitleList.get(position);         }     }      public void onButtonPressed(Uri uri) {         if (mListener != null) {             mListener.onFragmentInteraction(uri);         }     }      @Override     public void onAttach(Context context) {         super.onAttach(context);         if (context instanceof OnFragmentInteractionListener) {             mListener = (OnFragmentInteractionListener) context;         } else {             throw new RuntimeException(context.toString()                     + " must implement OnFragmentInteractionListener");         }     }      @Override     public void onDetach() {         super.onDetach();         mListener = null;     }      /**      * This interface must be implemented by activities that contain this      * fragment to allow an interaction in this fragment to be communicated      * to the activity and potentially other fragments contained in that      * activity.      * <p/>      * See the Android Training lesson <a href=      * "http://developer.android.com/training/basics/fragments/communicating.html"      * >Communicating with Other Fragments</a> for more information.      */     public interface OnFragmentInteractionListener {         void onFragmentInteraction(Uri uri);     } }

Full Source : https://github.com/herudi/EuroAppsAndroid

Apk : EuroApps.apk

Oke sekian dulu, mohon maaf bila ada kata2 yg kurang berkenan. akhir kata wassalamualaikum wr.wb.

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » membuat aplikasi jadwal dan klasmen EURO 2016 android featuring api football-data

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址