Commits

Giulio Piancastelli committed 4125472 Draft

Initial commit.

Comments (0)

Files changed (15)

+syntax: glob
+.classpath
+.project
+.settings
+bin
+gen
+*.properties
+proguard*.*

AndroidManifest.xml

+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.example.android.viewpagerdemo"
+    android:versionCode="1"
+    android:versionName="1.0" >
+
+    <uses-sdk
+        android:minSdkVersion="10"
+        android:targetSdkVersion="15" />
+
+    <application
+        android:icon="@drawable/ic_launcher"
+        android:label="@string/app_name"
+        android:theme="@style/AppTheme" >
+        <activity
+            android:name="MainActivity">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
+This is a throwaway demo for an Android application that will eventually have
+a slightly different navigation and data storage logic. It comprises of a
+ViewPager with five similar pages, each remembering how many times it has been
+swiped out and the time of the last swipe it went under. Data is saved in a
+SQLite database on each page being swiped out. Each page also features a
+ToggleButton: data for any page is saved only when its button is enabled. Two
+additional buttons are available on screen, to go directly to the first or last
+page. Functionality for dynamically adding a new page or deleting the page
+currently being displayed is missing, but would have been a nice extension to
+have.

libs/android-support-v4.jar

Binary file added.

res/drawable-hdpi/ic_launcher.png

Added
New image

res/drawable-mdpi/ic_launcher.png

Added
New image

res/drawable-xhdpi/ic_launcher.png

Added
New image

res/layout/main.xml

+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:orientation="vertical">
+
+    <TextView
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:gravity="center_horizontal"
+        android:text="@string/title"
+        style="@android:style/TextAppearance.Medium"
+        tools:context=".MainActivity" />
+    
+    <android.support.v4.view.ViewPager
+        android:id="@+id/pager"
+        android:layout_width="match_parent"
+        android:layout_height="0dp"
+        android:padding="15dp"
+        android:layout_weight="1" />
+    
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:gravity="center"
+        android:orientation="horizontal">
+        
+        <Button
+            android:id="@+id/first_button"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:text="@string/goto_first" />
+        
+        <Button
+            android:id="@+id/last_button"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:text="@string/goto_last" />
+        
+    </LinearLayout>
+
+</LinearLayout>

res/layout/page_fragment.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">
+    
+    <TextView
+        android:id="@+id/left_arrow"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_alignParentTop="true"
+        android:layout_alignParentLeft="true"
+        android:text="@string/left_arrow"
+        style="@android:style/TextAppearance.Large" />
+    
+    <TextView
+        android:id="@+id/right_arrow"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_alignParentTop="true"
+        android:layout_alignParentRight="true"
+        android:text="@string/right_arrow"
+        style="@android:style/TextAppearance.Large" />
+    
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="match_parent"
+        android:gravity="center"
+        android:layout_toRightOf="@id/left_arrow"
+        android:layout_toLeftOf="@id/right_arrow"
+        android:orientation="vertical">
+    
+	    <TextView
+	        android:id="@+id/swiped"
+	        android:layout_width="wrap_content"
+	        android:layout_height="wrap_content"
+	        android:text="@string/placeholder_number"
+	        style="@android:style/TextAppearance.Large" />
+	    
+	    <TextView
+	        android:id="@+id/latest_swipe"
+	        android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:text="@string/placeholder_text"
+            style="@android:style/TextAppearance.Large" />
+	    
+	</LinearLayout>
+	
+    <ToggleButton
+        android:id="@+id/page_toggle"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_alignParentBottom="true"
+        android:layout_centerHorizontal="true" />
+
+</RelativeLayout>

res/values/strings.xml

+<resources>
+
+    <string name="app_name">ViewPager-Demo</string>
+    <string name="title">ViewPager Demo</string>
+    <string name="goto_first">First</string>
+    <string name="goto_last">Last</string>
+    <string name="left_arrow">&lt;</string>
+    <string name="right_arrow">&gt;</string>
+    
+    <string name="placeholder_number">0</string>
+    <string name="placeholder_text">text</string>
+
+</resources>

res/values/styles.xml

+<resources>
+
+    <style name="AppTheme" parent="android:Theme.Black.NoTitleBar" />
+
+</resources>

src/com/example/android/viewpagerdemo/DatabaseAdapter.java

+package com.example.android.viewpagerdemo;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import android.content.ContentValues;
+import android.content.Context;
+import android.database.Cursor;
+import android.database.sqlite.SQLiteDatabase;
+import android.database.sqlite.SQLiteDatabase.CursorFactory;
+import android.database.sqlite.SQLiteException;
+import android.database.sqlite.SQLiteOpenHelper;
+import android.provider.BaseColumns;
+import android.util.Log;
+
+public class DatabaseAdapter {
+    
+    private static final String DATABASE_NAME = "demo.db";
+    private static final int DATABASE_VERSION = 1;
+    // database tables
+    private static final String PAGES_TABLE = "pages";
+    // primary key
+    private static final String KEY_ID = BaseColumns._ID;
+    private static final int ID_COLUMN = 0;
+    // columns for the pages table
+    private static final String KEY_NSWIPED = "n_swiped";
+    private static final int ID_NSWIPED = 1;
+    private static final String KEY_LATEST_SWIPE = "latest_swipe";
+    private static final int ID_LATEST_SWIPE = 2;
+    private static final String KEY_ENABLED = "enabled";
+    private static final int ID_ENABLED = 3;
+    // database creation SQL statements
+    private static final String CREATE_PAGES_TABLE =
+            "create table " + PAGES_TABLE + " (" +
+            KEY_ID + " integer primary key autoincrement, " +
+            KEY_NSWIPED + " integer not null, " +
+            KEY_LATEST_SWIPE + " integer not null, " +
+            KEY_ENABLED + " boolean default 1 not null" + ");";
+    
+    private SQLiteDatabase db;
+    private DatabaseHelper dbHelper;
+    
+    public DatabaseAdapter(Context context) {
+        dbHelper = new DatabaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
+    }
+    
+    public DatabaseAdapter open() {
+        try {
+            db = dbHelper.getWritableDatabase();
+        } catch (SQLiteException e) {
+            db = dbHelper.getReadableDatabase();
+        }
+        return this;
+    }
+
+    public void close() {
+        db.close();
+    }
+    
+    public List<Page> getAllPages() {
+        Cursor cursor = null;
+        List<Page> pages = new ArrayList<Page>();
+        try {
+            cursor = db.query(PAGES_TABLE,
+                              new String[] {KEY_ID, KEY_NSWIPED, KEY_LATEST_SWIPE, KEY_ENABLED},
+                              null, null, null, null, null);
+            if (cursor.moveToFirst()) {
+                do {
+                    Page page = new Page(cursor.getLong(ID_COLUMN),
+                                         cursor.getInt(ID_NSWIPED),
+                                         cursor.getLong(ID_LATEST_SWIPE),
+                                         cursor.getInt(ID_ENABLED) == 1);
+                    pages.add(page);
+                } while (cursor.moveToNext());
+            }
+            Page.setFirst(pages.get(0).getId());
+            Page.setLast(pages.get(pages.size() - 1).getId());
+            return pages;
+        } finally {
+            if (cursor != null) {
+                cursor.close();
+            }
+        }
+    }
+    
+//    public Page getPage(long id) {
+//        Cursor cursor = null;
+//        try {
+//            cursor = db.query(PAGES_TABLE, new String[] {KEY_ID, KEY_NSWIPED, KEY_LATEST_SWIPE},
+//                              KEY_ID + " = " + id, null, null, null, null, null);
+//            if (!cursor.moveToFirst()) {
+//                throw new SQLException("No Page found for ID: " + id);
+//            }
+//            return new Page(cursor.getLong(ID_COLUMN),
+//                            cursor.getInt(ID_NSWIPED),
+//                            cursor.getLong(ID_LATEST_SWIPE));
+//        } finally {
+//            if (cursor != null) {
+//                cursor.close();
+//            }
+//        }
+//    }
+    
+    public boolean save(Page page) {
+        ContentValues values = new ContentValues();
+        values.put(KEY_NSWIPED, page.getSwipeNumber());
+        values.put(KEY_LATEST_SWIPE, page.getLastSwiped());
+        values.put(KEY_ENABLED, page.isEnabled());
+        int affectedRows = db.update(PAGES_TABLE, values, KEY_ID + " = " + page.getId(), null);
+        return affectedRows > 0;
+    }
+    
+    private static class DatabaseHelper extends SQLiteOpenHelper {
+        public DatabaseHelper(Context context, String name, CursorFactory factory, int version) {
+            super(context, name, factory, version);
+        }
+
+        @Override
+        public void onCreate(SQLiteDatabase db) {
+            db.execSQL(CREATE_PAGES_TABLE);
+            for (ContentValues datum : getDemoData()) {
+                db.insert(PAGES_TABLE, null, datum);
+            }
+        }
+        
+        private List<ContentValues> getDemoData() {
+            List<ContentValues> data = new ArrayList<ContentValues>(Page.NUM_PAGES);
+            for (int i = 0; i < Page.NUM_PAGES; i++) {
+                ContentValues datum = new ContentValues();
+                datum.put(KEY_NSWIPED, 0);
+                datum.put(KEY_LATEST_SWIPE, 0L);
+                datum.put(KEY_ENABLED, true);
+                data.add(datum);
+            }
+            return data;
+        }
+
+        @Override
+        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
+            Log.w("DROLLEY", "Upgrading database" +
+                  " from " + oldVersion + " to " + newVersion +
+                  " which will destroy all old data");
+            db.execSQL("drop table if exists " + PAGES_TABLE);
+            onCreate(db);
+        }
+        
+    }
+
+}

src/com/example/android/viewpagerdemo/MainActivity.java

+package com.example.android.viewpagerdemo;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import android.os.Bundle;
+import android.support.v4.app.Fragment;
+import android.support.v4.app.FragmentActivity;
+import android.support.v4.app.FragmentManager;
+import android.support.v4.app.FragmentStatePagerAdapter;
+import android.support.v4.view.ViewPager;
+import android.support.v4.view.ViewPager.OnPageChangeListener;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.Button;
+
+public class MainActivity extends FragmentActivity {
+    
+    private ViewPager pager;
+    private PageAdapter adapter;
+    private DatabaseAdapter dbAdapter;
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.main);
+        dbAdapter = new DatabaseAdapter(getApplicationContext()).open();
+        pager = (ViewPager) findViewById(R.id.pager);
+        adapter = new PageAdapter(getSupportFragmentManager());
+        adapter.setPages(dbAdapter.getAllPages());
+        pager.setAdapter(adapter);
+        pager.setOnPageChangeListener(new PageSaver());
+        Button first = (Button) findViewById(R.id.first_button);
+        first.setOnClickListener(new OnClickListener() {
+            public void onClick(View v) {
+                pager.setCurrentItem(0);
+            }
+        });
+        Button last = (Button) findViewById(R.id.last_button);
+        last.setOnClickListener(new OnClickListener() {
+            public void onClick(View v) {
+                pager.setCurrentItem(Page.NUM_PAGES - 1);
+            }
+        });
+    }
+    
+    private void savePage(int position) {
+        PageFragment page = (PageFragment) adapter.getItem(position);
+        page.save(dbAdapter);
+    }
+
+    @Override
+    protected void onDestroy() {
+        super.onDestroy();
+        dbAdapter.close();
+    }
+    
+    private class PageSaver implements OnPageChangeListener {
+        private int currentPage;
+        
+        public PageSaver() {
+            this(0);
+        }
+        
+        public PageSaver(int initialPage) {
+            currentPage = initialPage;
+        }
+        
+        public void onPageSelected(int position) {
+            if (currentPage != position) {
+                savePage(currentPage);
+                currentPage = position;
+            }
+        }
+        
+        public void onPageScrolled(int position, float offset, int offsetPixels) {
+        }
+        
+        public void onPageScrollStateChanged(int state) {
+        }
+    }
+    
+    private static class PageAdapter extends FragmentStatePagerAdapter {
+        private List<Fragment> pages;
+        
+        public PageAdapter(FragmentManager fm) {
+            super(fm);
+        }
+        
+        public void setPages(List<Page> pages) {
+            this.pages = new ArrayList<Fragment>(pages.size());
+            for (Page page : pages) {
+                this.pages.add(PageFragment.createInstance(page));
+            }
+        }
+        
+        @Override
+        public Fragment getItem(int position) {
+            return pages.get(position);
+        }
+
+        @Override
+        public int getCount() {
+            return Page.NUM_PAGES;
+        }
+    }
+    
+}

src/com/example/android/viewpagerdemo/Page.java

+package com.example.android.viewpagerdemo;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+public class Page {
+    
+    public static final int NUM_PAGES = 5;
+    
+    private static final SimpleDateFormat FORMATTER = new SimpleDateFormat("HH:mm:ss, dd/MM/yyyy");
+    
+    private long id;
+    private int swipeNumber;
+    private long lastSwiped;
+    private boolean enabled;
+    
+    private static long firstId;
+    private static long lastId;
+    
+    public static void setFirst(long id) {
+        firstId = id;
+    }
+    
+    public static void setLast(long id) {
+        lastId = id;
+    }
+    
+    public Page(long id, int swipeNumber, long lastSwiped, boolean enabled) {
+        this.id = id;
+        this.swipeNumber = swipeNumber;
+        this.lastSwiped = lastSwiped;
+        this.enabled = enabled;
+    }
+    
+    public long getId() {
+        return id;
+    }
+    
+    public int getSwipeNumber() {
+        return swipeNumber;
+    }
+    
+    public long getLastSwiped() {
+        return lastSwiped;
+    }
+    
+    public String getLastSwipedAsFormattedString() {
+        Date date = new Date(lastSwiped);
+        return FORMATTER.format(date);
+    }
+    
+    public void setEnabled(boolean enabled) {
+        this.enabled = enabled;
+    }
+    
+    public boolean isEnabled() {
+        return enabled;
+    }
+    
+    public boolean isFirst() {
+        return id == firstId;
+    }
+    
+    public boolean isLast() {
+        return id == lastId;
+    }
+    
+    public void swiped() {
+        swipeNumber += 1;
+        lastSwiped = new Date().getTime();
+    }
+
+}

src/com/example/android/viewpagerdemo/PageFragment.java

+package com.example.android.viewpagerdemo;
+
+import android.os.Bundle;
+import android.support.v4.app.Fragment;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.TextView;
+import android.widget.ToggleButton;
+
+public class PageFragment extends Fragment {
+    
+    private static final String ARG_ID = "id";
+    private static final String ARG_NSWIPED = "nSwiped";
+    private static final String ARG_LATEST_SWIPE = "latestSwipe";
+    private static final String ARG_ENABLED = "enabled";
+    
+    private Page page;
+    
+    private TextView swiped;
+    private TextView latestSwiped;
+    private ToggleButton enabled;
+    
+    public static PageFragment createInstance(Page page) {
+        PageFragment fragment = new PageFragment();
+        Bundle args = new Bundle();
+        args.putLong(ARG_ID, page.getId());
+        args.putInt(ARG_NSWIPED, page.getSwipeNumber());
+        args.putLong(ARG_LATEST_SWIPE, page.getLastSwiped());
+        args.putBoolean(ARG_ENABLED, page.isEnabled());
+        fragment.setArguments(args);
+        return fragment;
+    }
+    
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        Bundle args = getArguments();
+        if (args != null) {
+            page = new Page(args.getLong(ARG_ID),
+                            args.getInt(ARG_NSWIPED),
+                            args.getLong(ARG_LATEST_SWIPE),
+                            args.getBoolean(ARG_ENABLED));
+        }
+    }
+    
+    @Override
+    public View onCreateView(LayoutInflater inflater,
+                             ViewGroup container, Bundle savedInstanceState) {
+        View view = inflater.inflate(R.layout.page_fragment, container, false);
+        if (isFirst()) {
+            View leftArrow = view.findViewById(R.id.left_arrow);
+            leftArrow.setVisibility(View.INVISIBLE);
+        }
+        if (isLast()) {
+            View rightArrow = view.findViewById(R.id.right_arrow);
+            rightArrow.setVisibility(View.INVISIBLE);
+        }
+        swiped = (TextView) view.findViewById(R.id.swiped);
+        latestSwiped = (TextView) view.findViewById(R.id.latest_swipe);
+        enabled = (ToggleButton) view.findViewById(R.id.page_toggle);
+        if (savedInstanceState != null) {
+            page = new Page(savedInstanceState.getLong(ARG_ID),
+                            savedInstanceState.getInt(ARG_NSWIPED),
+                            savedInstanceState.getLong(ARG_LATEST_SWIPE),
+                            savedInstanceState.getBoolean(ARG_ENABLED));
+        }
+        refresh();
+        return view;
+    }
+
+    private void refresh() {
+        swiped.setText(String.valueOf(page.getSwipeNumber()));
+        String latest = page.getLastSwiped() == 0
+                        ? "never"
+                        : "on " + page.getLastSwipedAsFormattedString();
+        latestSwiped.setText("Latest swiped: " + latest);
+        enabled.setChecked(page.isEnabled());
+    }
+    
+    private boolean isFirst() {
+        return page.isFirst();
+    }
+    
+    private boolean isLast() {
+        return page.isLast();
+    }
+    
+    @Override
+    public void onSaveInstanceState(Bundle outState) {
+        super.onSaveInstanceState(outState);
+        outState.putLong(ARG_ID, page.getId());
+        outState.putInt(ARG_NSWIPED, page.getSwipeNumber());
+        outState.putLong(ARG_LATEST_SWIPE, page.getLastSwiped());
+        outState.putBoolean(ARG_ENABLED, page.isEnabled());
+    }
+    
+    public void save(DatabaseAdapter dbAdapter) {
+        page.setEnabled(enabled.isChecked());
+        if (page.isEnabled()) {
+            page.swiped();
+        }
+        dbAdapter.save(page);
+        refresh();
+    }
+
+}