Merge branch 'dev'

This commit is contained in:
Tariel Hlontsi 2016-07-24 11:11:25 +03:00
commit 3ace787762
158 changed files with 7519 additions and 2575 deletions

View File

@ -24,11 +24,16 @@ android {
}
}
repositories {
mavenCentral()
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.0.1'
compile 'com.squareup.retrofit2:converter-gson:2.0.1'
@ -38,4 +43,5 @@ dependencies {
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.android.support:design:23.3.0'
compile 'com.android.support:cardview-v7:23.3.0'
compile 'com.facebook.android:facebook-android-sdk:4.11.0'
}

BIN
app/libs/socialauth-4.4.jar Normal file

Binary file not shown.

Binary file not shown.

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack;
package com.hikapro.backpack;
import android.app.Application;
import android.test.ApplicationTestCase;

View File

@ -1,23 +1,33 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="hikapro.com.backpack">
package="com.hikapro.backpack">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:name=".App"
android:name="com.hikapro.backpack.App"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
<activity android:name="com.hikapro.backpack.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:label="@string/app_name" />
</application>
</manifest>

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1 @@
[{"id":16,"name":"Bug Sprays"},{"id":1,"name":"Clothing"},{"id":8,"name":"Documents"},{"id":11,"name":"Electronics"},{"id":3,"name":"Equipment"},{"id":14,"name":"Furniture"},{"id":7,"name":"Groceries"},{"id":4,"name":"Medicines"},{"id":5,"name":"Personal Care"},{"id":15,"name":"Tools"},{"id":2,"name":"Utensils"}]

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1 @@
[{"id":4,"item_ids":[212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,254,256,258,259,261,253,257,262,270,275,296,295,297,300,298,308,306,309,310,311,313,318,319,320,321,322,315,323,325,326,327,329,331,333,335,336,337,338,339,340,341,377,348,349,351,352,391,379,353,380,355,381,382,383,358,360,361,362,363,378,384,365,366,367,385,368,386,369,387,371,372,388,374,394,403,395,400,397,398],"name":"Alpine","photo":"","photo_thumb":"","photo_thumbnail":""},{"id":5,"item_ids":[212,213,214,216,217,218,220,221,222,224,225,226,227,228,229,230,231,233,235,236,237,238,239,240,241,242,249,250,243,244,264,251,245,246,247,255,248,256,252,261,253,293,294,299,304,305,309,310,312,317,318,327,328,329,331,333,334,335,336,337,338,343,339,341,342,344,345,346,347,348,353,355,359,362,363,364,368,369,370,374,394,402,400,401,398,258,259,262,275,270,406,223,215,409,232,411,412],"name":"Caravanning","photo":"","photo_thumb":"","photo_thumbnail":""},{"id":8,"item_ids":[212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,228,230,231,232,233,234,235,236,237,238,239,254,256,258,259,260,261,253,257,262,270,275,299,303,305,306,309,310,311,312,314,316,317,321,315,327,328,329,331,332,333,334,335,336,337,338,343,339,340,341,342,344,345,346,377,389,390,348,349,352,379,353,380,383,358,392,362,363,364,378,384,365,366,367,368,386,369,387,370,371,388,373,374,403,395,391,396,400,397,398],"name":"Caving","photo":"","photo_thumb":"","photo_thumbnail":""},{"id":3,"item_ids":[279,282,273,274,288,283,291,289,271,267,268,269,270,266,278,286,277,272,280,281,265,284,285,287,276,290,292],"name":"First-aid kit","photo":"","photo_thumb":"","photo_thumbnail":""},{"id":15,"item_ids":[],"name":"My list","photo":"","photo_thumb":"","photo_thumbnail":""},{"id":2,"item_ids":[212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,238,249,264,254,255,258,259,252,261,253,262,270,275,299,303,304,306,309,310,311,312,316,317,318,327,328,329,331,332,333,334,335,336,337,338,343,339,340,341,342,344,345,346,375,347,348,350,353,359,362,363,364,365,367,368,376,369,370,374,403,395,400,397,398],"name":"Rafting","photo":"","photo_thumb":"","photo_thumbnail":""},{"id":14,"item_ids":[409,217,218,224,225,227,232,234,235,238,254,275,292,295,296,297,421,306,309,310,311,317,318,315,323,327,329,420,332,340,416,427,424,426,425,380,357,417,418,422,419,415,423,374,408,405,404,400,401,428],"name":"Ski / Snowboard","photo":"","photo_thumb":"","photo_thumbnail":""},{"id":1,"item_ids":[212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,254,256,258,259,261,253,262,270,275,296,299,304,330,306,309,310,311,312,316,317,318,320,321,325,326,327,328,329,331,332,333,334,335,336,337,338,343,339,341,342,344,345,346,347,348,349,352,353,354,355,356,360,361,362,363,364,365,367,368,369,370,372,373,374,394,403,395,400,397,398,413],"name":"Summer hiking","photo":"","photo_thumb":"","photo_thumbnail":""},{"id":6,"item_ids":[212,213,214,215,216,217,218,219,220,222,224,225,226,228,231,232,233,235,236,237,238,239,275,299,305,309,310,311,317,318,325,326,327,328,329,332,374,399,400,401,393,398,405,404,340],"name":"Trip","photo":"","photo_thumb":"","photo_thumbnail":""},{"id":10,"item_ids":[223,214,215,409,217,218,219,220,224,225,226,230,234,235,239,264,261,253,270,275,295,297,300,298,308,309,310,311,313,318,320,321,315,324,326,329,332,333,335,336,337,338,339,340,341,331,349,352,353,354,355,356,357,361,362,363,364,365,366,367,368,369,372,374,394,408,395,400,397],"name":"Winter hiking","photo":"","photo_thumb":"","photo_thumbnail":""}]

View File

@ -1,7 +1,8 @@
package hikapro.com.backpack;
package com.hikapro.backpack;
import android.app.Application;
import android.content.Context;
import android.graphics.Typeface;
/**
* Created by tariel on 27/04/16.
@ -9,14 +10,20 @@ import android.content.Context;
public class App extends Application {
private static Context context;
private static Typeface mainFace;
@Override
public void onCreate() {
super.onCreate();
App.context = getApplicationContext();
App.mainFace = Typeface.createFromAsset(App.context.getAssets(), "fonts/Ubuntu-B.ttf");
}
public static Context getAppContext() {
return App.context;
}
public static Typeface getMainFace() {
return App.mainFace;
}
}

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack;
package com.hikapro.backpack;
import android.app.Activity;
import android.app.Fragment;
@ -6,23 +6,31 @@ import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import hikapro.com.backpack.model.DetailModel;
import hikapro.com.backpack.model.ItemModel;
import hikapro.com.backpack.model.PackedModel;
import hikapro.com.backpack.model.SetModel;
import hikapro.com.backpack.model.entities.Item;
import hikapro.com.backpack.model.entities.Set;
import hikapro.com.backpack.presenter.ItemDetailPresenter;
import hikapro.com.backpack.presenter.ItemListPresenter;
import hikapro.com.backpack.presenter.PackedListPresenter;
import hikapro.com.backpack.presenter.Presenter;
import hikapro.com.backpack.presenter.SetListPresenter;
import hikapro.com.backpack.view.View;
import hikapro.com.backpack.view.fragments.ItemDetailFragment;
import hikapro.com.backpack.view.fragments.ItemListFragment;
import hikapro.com.backpack.view.fragments.PackedListFragment;
import hikapro.com.backpack.view.fragments.SetListFragment;
import com.hikapro.backpack.model.AddModel;
import com.hikapro.backpack.model.DetailModel;
import com.hikapro.backpack.model.ItemModel;
import com.hikapro.backpack.model.Model;
import com.hikapro.backpack.model.PackedModel;
import com.hikapro.backpack.model.SetModel;
import com.hikapro.backpack.model.ShareModel;
import com.hikapro.backpack.model.entities.Item;
import com.hikapro.backpack.model.entities.Set;
import com.hikapro.backpack.presenter.AddPresenter;
import com.hikapro.backpack.presenter.ItemDetailPresenter;
import com.hikapro.backpack.presenter.ItemListPresenter;
import com.hikapro.backpack.presenter.PackedListPresenter;
import com.hikapro.backpack.presenter.Presenter;
import com.hikapro.backpack.presenter.SetListPresenter;
import com.hikapro.backpack.presenter.SharePresenter;
import com.hikapro.backpack.view.View;
import com.hikapro.backpack.view.fragments.AddFragment;
import com.hikapro.backpack.view.fragments.ItemDetailFragment;
import com.hikapro.backpack.view.fragments.ItemListFragment;
import com.hikapro.backpack.view.fragments.PackedListFragment;
import com.hikapro.backpack.view.fragments.SetListFragment;
import com.hikapro.backpack.view.fragments.ShareFragment;
public class MainActivity extends Activity implements View.ActivityCallback {
@ -34,6 +42,21 @@ public class MainActivity extends Activity implements View.ActivityCallback {
// life cycle -->
@Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean ret;
switch (item.getItemId()) {
case android.R.id.home:
this.getFragmentManager().popBackStack();
ret = true;
break;
default:
ret = super.onOptionsItemSelected(item);
}
return ret;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -42,7 +65,6 @@ public class MainActivity extends Activity implements View.ActivityCallback {
stateMaintainer.init();
if (fragmentManager.getBackStackEntryCount() == 0 && savedInstanceState == null) {
startSetListFragment();
} else {
@ -82,6 +104,7 @@ public class MainActivity extends Activity implements View.ActivityCallback {
presenter.setModel(model);
model.setPresenter(presenter);
}
fragment = fragmentManager.findFragmentByTag(PackedListFragment.class.getName());
if (fragment != null) {
PackedListFragment view = (PackedListFragment) fragment;
@ -93,6 +116,30 @@ public class MainActivity extends Activity implements View.ActivityCallback {
presenter.setModel(model);
model.setPresenter(presenter);
}
fragment = fragmentManager.findFragmentByTag(ShareFragment.class.getName());
if (fragment != null) {
ShareFragment view = (ShareFragment) fragment;
SharePresenter presenter = stateMaintainer.get(SharePresenter.class.getName());
ShareModel model = stateMaintainer.get(ShareModel.class.getName());
view.setPresenter(presenter);
presenter.setView(view);
presenter.setModel(model);
model.setPresenter(presenter);
}
fragment = fragmentManager.findFragmentByTag(AddFragment.class.getName());
if (fragment != null) {
AddFragment view = (AddFragment) fragment;
AddPresenter presenter = stateMaintainer.get(AddPresenter.class.getName());
AddModel model = stateMaintainer.get(AddModel.class.getName());
view.setPresenter(presenter);
presenter.setView(view);
presenter.setModel(model);
model.setPresenter(presenter);
}
}
Log.i("On create", "Activity");
}
@ -147,7 +194,6 @@ public class MainActivity extends Activity implements View.ActivityCallback {
presenter.setModel(model);
model.setPresenter(presenter);
//replaceFragment(view, false, SetListFragment.class.getName(), false, false);
replaceFragment(view, SetListFragment.class.getName(), 0);
stateMaintainer.put(presenter);
stateMaintainer.put(model);
@ -166,7 +212,6 @@ public class MainActivity extends Activity implements View.ActivityCallback {
presenter.setModel(model);
model.setPresenter(presenter);
//replaceFragment(view, true, ItemListFragment.class.getName(), true, true);
replaceFragment(view, ItemListFragment.class.getName(),
Presenter.ADD_TO_BACKSTACK | Presenter.TRANSITION_X);
@ -191,7 +236,6 @@ public class MainActivity extends Activity implements View.ActivityCallback {
presenter.setModel(model);
model.setPresenter(presenter);
//replaceFragment(view, true, ItemListFragment.class.getName(), true, true);
replaceFragment(view, PackedListFragment.class.getName(),
Presenter.ADD_TO_BACKSTACK | Presenter.TRANSITION_Y);
@ -201,10 +245,10 @@ public class MainActivity extends Activity implements View.ActivityCallback {
}
@Override
public void startItemDetailFragment(Item item) {
public void startItemDetailFragment(int setId, Model.Item baseModel, int position) {
ItemDetailFragment view = ItemDetailFragment.newFromItem(item);
ItemDetailPresenter presenter = new ItemDetailPresenter();
ItemDetailFragment view = ItemDetailFragment.newInstance(setId);
ItemDetailPresenter presenter = new ItemDetailPresenter(baseModel, position);
DetailModel model = new DetailModel();
view.setPresenter(presenter);
@ -212,28 +256,49 @@ public class MainActivity extends Activity implements View.ActivityCallback {
presenter.setModel(model);
model.setPresenter(presenter);
//replaceFragment(view, true, ItemDetailFragment.class.getName(), true, true);
replaceFragment(view, ItemDetailFragment.class.getName(),
Presenter.ADD_TO_BACKSTACK | Presenter.TRANSITION_X);
stateMaintainer.put(presenter);
stateMaintainer.put(model);
}
@Override
public void startShareFragment(int setId) {
ShareFragment view = ShareFragment.construct();
SharePresenter presenter = new SharePresenter();
ShareModel model = new ShareModel();
view.setPresenter(presenter);
presenter.setView(view);
presenter.setModel(model);
model.setPresenter(presenter);
replaceFragment(view, ShareFragment.class.getName(),
Presenter.ADD_TO_BACKSTACK | Presenter.TRANSITION_X);
stateMaintainer.put(presenter);
stateMaintainer.put(model);
}
private void replaceFragment(Fragment fragment, boolean addBackStack, String tag,
boolean transition, boolean x) {
FragmentTransaction transaction = fragmentManager.beginTransaction();
if (transition) {
if (x)
transaction.setCustomAnimations(R.animator.slide_in_left_x, R.animator.slide_out_right_x,
R.animator.slide_in_right_x, R.animator.slide_out_left_x);
}
@Override
public void startAddFragment(Set set) {
AddFragment view = AddFragment.newFromSet(set);
AddPresenter presenter = new AddPresenter();
AddModel model = new AddModel();
transaction.replace(R.id.container, fragment, tag);
if (addBackStack)
transaction.addToBackStack(null);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.commit();
view.setPresenter(presenter);
presenter.setView(view);
presenter.setModel(model);
model.setPresenter(presenter);
replaceFragment(view, AddFragment.class.getName(),
Presenter.ADD_TO_BACKSTACK | Presenter.TRANSITION_X);
stateMaintainer.put(presenter);
stateMaintainer.put(model);
}
private void replaceFragment(Fragment fragment, String tag, int flags) {

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack;
package com.hikapro.backpack;
import android.app.Fragment;
import android.app.FragmentManager;
@ -79,7 +79,6 @@ public class StateMaintainer {
public void put(String key, Object obj) {
data.put(key, obj);
Log.i(this.toString(), String.format("Put object %s Total count %d", key, data.size()));
}

View File

@ -0,0 +1,154 @@
package com.hikapro.backpack.model;
import android.os.Message;
import android.widget.Toast;
import com.hikapro.backpack.App;
import com.hikapro.backpack.model.dao.Command;
import com.hikapro.backpack.model.dao.DAO;
import com.hikapro.backpack.model.dao.Event;
import com.hikapro.backpack.model.entities.Category;
import com.hikapro.backpack.model.entities.Item;
import com.hikapro.backpack.presenter.Presenter;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
/**
* Created by tariel on 18/05/16.
*/
public class AddModel implements Model.Add {
private Presenter.Add presenter;
private DAO dao;
private List<Item> filteredItems;
private List<Category> categoriesCache;
public AddModel() {
this.filteredItems = new ArrayList<>(256);
this.categoriesCache = new ArrayList<>(20);
this.dao = DAO.getInstance();
dao.registerObserver(this);
}
@Override
public void onEvent(Message event) {
switch (event.what) {
case Event.ITEM_LIKE_LOAD_ERROR :
if (!filteredItems.isEmpty()) {
filteredItems.clear();
}
notifyDataSetChanged();
break;
case Event.ITEM_CATEGORY_LOAD_ERROR :
break;
case Event.ITEM_INSERT_ERROR :
Toast.makeText(App.getAppContext(), "Item not inserted!", Toast.LENGTH_SHORT).show();
break;
case Event.ITEM_LIKE_LOAD_COMPLETED :
filteredItems = (List<Item>) event.obj;
notifyDataSetChanged();
break;
case Event.ITEM_CATEGORY_LOAD_COMPLETED :
Hashtable<Integer, Category> res = (Hashtable<Integer, Category>)event.obj;
categoriesCache = new ArrayList<>(res.values()); // TODO check utilization
break;
case Event.ITEM_INSERTED :
Toast.makeText(App.getAppContext(), "New item inserted", Toast.LENGTH_SHORT).show();
break;
}
}
@Override
public void onDestroy(boolean isConfigurationChanging) {
if ( !isConfigurationChanging ) {
presenter = null;
}
}
@Override
public void executeQuery() {
Message command;
if (categoriesCache.isEmpty()) {
command = Message.obtain();
command.what = Command.ITEM_GET_CATEGORIES;
dao.executeCommand(command);
}
}
@Override
public void add(Item item, int setId) {
Message command;
command = Message.obtain();
command.what = Command.ITEM_INSERT;
command.obj = item;
command.arg1 = setId;
dao.executeCommand(command);
}
@Override
public void filter(String query, int checkThisSet) {
if (!query.isEmpty()) {
Message command = Message.obtain();
command.what = Command.ITEM_GET_LIKE;
command.arg1 = checkThisSet;
query = query.toLowerCase();
command.obj = query;
dao.executeCommand(command);
}
}
@Override
public void notifyDataSetChanged() {
boolean res = !filteredItems.isEmpty();
presenter.notifyDataSetChanged(res);
}
@Override
public int getItemsCount() {
return filteredItems.size();
}
@Override
public Item getItemByPosition(int position) {
return filteredItems.get(position);
}
@Override
public int getCategoriesCount() {
return categoriesCache.size();
}
@Override
public Category getCategoryByPosition(int position) {
return categoriesCache.get(position);
}
@Override
public Category getCategoryById(int id) {
for (Category category : categoriesCache) {
if (category.getId() == id)
return category;
}
return null;
}
@Override
public void setPresenter(Presenter.Add presenter) {
this.presenter = presenter;
}
@Override
public Presenter.Add getPresenter() {
return presenter;
}
}

View File

@ -0,0 +1,36 @@
package com.hikapro.backpack.model;
import java.util.List;
import com.hikapro.backpack.model.entities.Category;
import com.hikapro.backpack.model.entities.Item;
import com.hikapro.backpack.model.entities.Set;
import com.hikapro.backpack.model.entities.Timestamp;
import com.hikapro.backpack.model.entities.Updates;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
/**
* Created by tariel on 19/04/16.
*/
public interface Api {
@GET("api/v1/backpack/items")
Call<List<Item>> getItems(@Query("locale") String locale);
@GET("api/v1/backpack/item_categories")
Call<List<Category>> getItemCategories(@Query("locale") String locale);
@GET("api/v1/backpack/sets")
Call<List<Set>> getSets(@Query("locale") String locale);
@GET("api/v1/backpack/updates/timestamp")
Call<Timestamp> getTimestamp();
@GET("api/v1/backpack/updates/all")
Call<Updates> getUpdates(@Query("timestamp") long timestamp);
}

View File

@ -0,0 +1,189 @@
package com.hikapro.backpack.model;
import android.graphics.Bitmap;
import android.os.Message;
import android.widget.Toast;
import com.hikapro.backpack.App;
import com.hikapro.backpack.model.dao.Command;
import com.hikapro.backpack.model.dao.DAO;
import com.hikapro.backpack.model.dao.Event;
import com.hikapro.backpack.model.entities.Item;
import com.hikapro.backpack.presenter.Presenter;
import java.util.Collections;
/**
* Created by tariel on 23/04/16.
*/
public class DetailModel implements Model.Detail {
private Presenter.ItemDetail presenter;
private Item item;
private DAO dao;
private Bitmap pic;
private int currentSet;
public DetailModel() {
this.dao = DAO.getInstance();
}
// detail -->
@Override
public int getCount() {
return 1;
}
@Override
public Item getCurrentItem() {
return item;
}
@Override
public void setCurrentItem(Item item) {
this.item = item;
}
@Override
public Bitmap getPicture() {
return pic;
}
// detail <--
// events -->
@Override
public void notifyDataSetChanged() {
if (presenter != null)
presenter.notifyDataSetChanged();
}
@Override
public void onDestroy(boolean isConfigurationChanging) {
if ( !isConfigurationChanging ) {
presenter = null;
}
dao.unregisterObserver(this);
}
// events <--
// process -->
@Override
public void executeQuery() {
dao.registerObserver(this);
Message command = Message.obtain();
command.what = Command.ITEM_READ;
command.arg1 = currentSet;
command.arg2 = item.getId();
dao.executeCommand(command);
command = Message.obtain();
command.what = Command.ITEM_GET_IMAGE;
command.arg1 = item.getId();
dao.executeCommand(command);
}
@Override
public void pendingRemove(Item item) {
if (item != null) {
Message command = Message.obtain();
command.what = Command.ITEM_PENDING_REMOVAL;
command.arg1 = currentSet;
command.arg2 = item.getId();
dao.executeCommand(command);
}
}
@Override
public void pendingRemoveCancel(Item item) {
if (item != null) {
Message command = Message.obtain();
command.what = Command.ITEM_REMOVAL_CANCEL;
command.arg1 = currentSet;
command.arg2 = item.getId();
dao.executeCommand(command);
}
}
@Override
public void packItem(Item item) {
if (item != null) {
Message command = Message.obtain();
command.what = Command.ITEM_PACK;
command.arg1 = currentSet;
command.arg2 = item.getId();
dao.executeCommand(command);
}
}
@Override
public void unpackItem(Item item) {
if (item != null) {
Message command = Message.obtain();
command.what = Command.ITEM_UNPACK;
command.arg1 = currentSet;
command.arg2 = item.getId();
dao.executeCommand(command);
}
}
// process <--
@Override
public void setPresenter(Presenter.ItemDetail presenter) {
this.presenter = presenter;
this.currentSet = presenter.getSetId();
}
@Override
public Presenter.ItemDetail getPresenter() {
return presenter;
}
@Override
public void onEvent(Message event) {
switch (event.what) {
case Event.ITEM_IMAGE_LOAD_ERROR:
pic = null;
if (presenter != null)
presenter.notifyPictureChanged();
break;
case Event.ITEM_READ_ERROR:
Toast.makeText(App.getAppContext(), "Item read error", Toast.LENGTH_SHORT).show();
break;
case Event.ITEM_PACK_ERROR:
break;
case Event.ITEM_UNPACK_ERROR:
break;
case Event.ITEM_PENDING_REMOVAL_ERROR:
break;
case Event.ITEM_REMOVAL_CANCEL_ERROR:
break;
case Event.ITEM_IMAGE_LOAD_COMPLETED:
pic = (Bitmap) event.obj;
if (presenter != null)
presenter.notifyPictureChanged();
break;
case Event.ITEM_PACKED:
executeQuery();
break;
case Event.ITEM_UNPACKED:
executeQuery();
case Event.ITEM_PENDING_REMOVAL_COMPLETED:
executeQuery();
case Event.ITEM_REMOVAL_CANCELED:
executeQuery();
break;
case Event.ITEM_READ_COMPLETED:
item = (Item) event.obj;
notifyDataSetChanged();
break;
}
}
}

View File

@ -0,0 +1,342 @@
package com.hikapro.backpack.model;
import android.os.Message;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import com.hikapro.backpack.App;
import com.hikapro.backpack.model.dao.Command;
import com.hikapro.backpack.model.dao.DAO;
import com.hikapro.backpack.model.dao.Event;
import com.hikapro.backpack.model.entities.Category;
import com.hikapro.backpack.model.entities.Item;
import com.hikapro.backpack.presenter.Presenter;
/**
* Created by tariel on 22/04/16.
*/
public class ItemModel implements Model.Item {
protected Presenter.ItemList presenter;
protected DAO dao;
protected int currentSet;
protected int currentSetActiveItemsQty;
protected int packedQty;
protected Hashtable<Integer, Category> categoriesCache;
protected List<Item> itemsCache;
protected Hashtable<Category, List<Item>> items;
public ItemModel() {
this.categoriesCache = new Hashtable<>(20, 0.9f);
this.itemsCache = new ArrayList<>(256);
this.packedQty = -1;
this.dao = DAO.getInstance();
}
@Override
public void onEvent(Message event) {
switch (event.what) {
case Event.SET_ITEMS_LOAD_ERROR : // TODO check
if (presenter != null) {
if (packedQty == -1)
packedQty = presenter.getCurrentSet().getPackedQty();
presenter.notifyItemPackStatusChanged();
}
break;
case Event.SET_UNPACK_ERROR :
break;
case Event.SET_RESTORE_ERROR :
break;
case Event.SET_GET_STAT_ERROR:
break;
case Event.ITEM_FROM_SET_ERROR :
break;
case Event.ITEM_DELETE_ERROR :
break;
case Event.ITEM_PACK_ERROR :
break;
case Event.ITEM_UNPACK_ERROR :
break;
case Event.ITEM_INSERT_ERROR :
break;
case Event.ITEM_PENDING_REMOVAL_ERROR:
break;
case Event.ITEM_REMOVAL_CANCEL_ERROR:
break;
case Event.ITEM_CATEGORY_LOAD_ERROR :
break;
case Event.SET_ITEMS_LIKE_ERROR:
if (!itemsCache.isEmpty()) {
itemsCache.clear();
}
notifyDataSetChanged();
break;
case Event.SET_ITEMS_LOAD_COMPLETED:
itemsCache = (List<Item>) event.obj;
notifyDataSetChanged();
break;
case Event.SET_ITEMS_LIKE_COMPLETED:
itemsCache = (List<Item>) event.obj;
notifyDataSetChanged();
break;
case Event.SET_GET_STAT_COMPLETED:
currentSetActiveItemsQty = event.arg1;
packedQty = event.arg2;
if (presenter != null)
presenter.notifyItemPackStatusChanged();
break;
case Event.ITEM_PENDING_REMOVAL_COMPLETED:
executeQuery();
break;
case Event.ITEM_REMOVAL_CANCELED:
executeQuery();
break;
case Event.ITEM_READ_COMPLETED:
itemsCache.add((Item) event.obj);
Collections.sort(itemsCache);
notifyDataSetChanged();
break;
case Event.SET_UNPACK_COMPLETED:
executeQuery();
break;
case Event.ITEM_CATEGORY_LOAD_COMPLETED:
categoriesCache = (Hashtable<Integer, Category>)event.obj;
break;
case Event.ITEM_FROM_SET_DELETED:
executeQuery();
break;
case Event.ITEM_DELETED :
break;
case Event.ITEM_PACKED :
executeQuery();
break;
case Event.ITEM_UNPACKED :
executeQuery();
break;
case Event.ITEM_INSERTED :
break;
case Event.SET_RESTORE_COMPLETED:
executeQuery();
Toast.makeText(App.getAppContext(), "Restore completed", Toast.LENGTH_SHORT).show();
break;
}
}
@Override
public void executeQuery() {
Message command;
dao.registerObserver(this);
command = Message.obtain();
command.what = Command.SET_CLEAN_PACKED;
command.arg1 = currentSet;
dao.executeCommand(command);
if (categoriesCache.isEmpty()) {
command = Message.obtain();
command.what = Command.ITEM_GET_CATEGORIES;
dao.executeCommand(command);
}
command = Message.obtain();
command.what = Command.SET_GET_ITEMS;
command.arg1 = currentSet;
dao.executeCommand(command);
command = Message.obtain();
command.what = Command.SET_GET_STAT;
command.arg1 = presenter.getCurrentSet().getId();
dao.executeCommand(command);
}
// categories -->
@Override
public Category getCategoryByPosition(int position) {
Category ret = null;
ret = categoriesCache.get(itemsCache.get(position).getCategory());
return ret;
}
// categories <--
// items -->
@Override
public Item findItem(int id) {
Item item = null;
for (Item i : itemsCache) {
if (i.getId() == id) {
item = i;
break;
}
}
return item;
}
@Override
public Item getItemByPosition(int position) {
Item ret = null;
ret = itemsCache.get(position);
return ret;
}
@Override
public void filter(String query) {
if (query.isEmpty()) {
Message command = Message.obtain();
command.what = Command.SET_GET_ITEMS;
command.arg1 = presenter.getCurrentSet().getId();
dao.executeCommand(command);
} else {
Message command = Message.obtain();
command.what = Command.SET_GET_ITEMS_LIKE;
command.arg1 = presenter.getCurrentSet().getId();
command.obj = query;
dao.executeCommand(command);
}
}
@Override
public int getHeaderId(int position) {
return itemsCache.get(position).getCategory();
}
@Override
public int getItemId(int position) {
return itemsCache.get(position).getId();
}
@Override
public int getItemsCount() {
return itemsCache.size();
}
@Override
public int getActiveItemsCount() {
return currentSetActiveItemsQty;
}
@Override
public int getPackedQty() {
return packedQty;
}
// items <--
// events -->
@Override
public void notifyDataSetChanged() {
if (presenter != null)
presenter.notifyDataSetChanged();
}
@Override
public void onDestroy(boolean isConfigurationChanging) {
if ( !isConfigurationChanging ) {
presenter = null;
}
dao.unregisterObserver(this);
}
// events <--
// process -->
@Override
public void pendingRemove(Item item) {
if (item != null) {
Message command = Message.obtain();
command.what = Command.ITEM_PENDING_REMOVAL;
command.arg1 = currentSet;
command.arg2 = item.getId();
dao.executeCommand(command);
//itemsCache.remove(item);// TODO check nn
}
}
@Override
public void pendingRemoveCancel(Item item) {
if (item != null) {
Message command = Message.obtain();
command.what = Command.ITEM_REMOVAL_CANCEL;
command.arg1 = currentSet;
command.arg2 = item.getId();
dao.executeCommand(command);
//itemsCache.remove(item);
}
}
@Override
public void remove(Item item) {
if (item != null) {
Message command = Message.obtain();
command.what = Command.ITEM_DELETE_FROM_SET;
command.arg1 = currentSet;
command.arg2 = item.getId();
dao.executeCommand(command);
//itemsCache.remove(item);
}
}
@Override
public void packItem(com.hikapro.backpack.model.entities.Item item) {
if (item != null) {
itemsCache.remove(item);
Message command = Message.obtain();
command.what = Command.ITEM_PACK;
command.arg1 = currentSet;
command.arg2 = item.getId();
dao.executeCommand(command);
}
}
@Override
public void unpackItem(com.hikapro.backpack.model.entities.Item item) {
// nothing
}
@Override
public void unpackSet(int setId) {
Message command;
command = Message.obtain();
command.what = Command.SET_UNPACK_ITEMS;
command.arg1 = setId;
dao.executeCommand(command);
}
@Override
public void restoreSet(int setId) {
Message command;
command = Message.obtain();
command.what = Command.SET_RESTORE_DEFAULT;
command.arg1 = presenter.getCurrentSet().getId();
dao.executeCommand(command);
}
// process <--
// other -->
@Override
public void setPresenter(Presenter.ItemList presenter) {
this.presenter = presenter;
this.currentSet = presenter.getCurrentSet().getId();
this.currentSetActiveItemsQty = presenter.getCurrentSet().getActiveQty();
//dao.registerObserver(this);
}
@Override
public Presenter.ItemList getPresenter() {
return presenter;
}
// other <--
}

View File

@ -0,0 +1,94 @@
package com.hikapro.backpack.model;
import android.graphics.Bitmap;
import android.os.Message;
import java.util.List;
import com.hikapro.backpack.model.entities.Category;
import com.hikapro.backpack.model.entities.Item;
import com.hikapro.backpack.presenter.Presenter;
/**
* Created by tariel on 19/04/16.
*/
public interface Model {
interface Base {
void onDestroy(boolean isConfigurationChanging);
void executeQuery();
void notifyDataSetChanged();
void onEvent(Message event);
}
interface Set extends Base {
com.hikapro.backpack.model.entities.Set getSetByPosition(int position);
com.hikapro.backpack.model.entities.Set findSet(int id);
int getSetsCount();
void setPresenter(Presenter.SetList presenter);
Presenter.SetList getPresenter();
//GLM
List<com.hikapro.backpack.model.entities.Set> getSets(); // tag renamed
void setsReorderNotify();
}
interface Item extends Base {
void filter(String query);
int getHeaderId(int position);//TODO review
int getItemId(int position);//TODO review
// leave at home
void pendingRemove(com.hikapro.backpack.model.entities.Item item);
void pendingRemoveCancel(com.hikapro.backpack.model.entities.Item item);
void remove(com.hikapro.backpack.model.entities.Item item);
int getItemsCount();
int getActiveItemsCount();
int getPackedQty();
com.hikapro.backpack.model.entities.Item findItem(int id);
com.hikapro.backpack.model.entities.Item getItemByPosition(int position);
com.hikapro.backpack.model.entities.Category getCategoryByPosition(int position);
void setPresenter(Presenter.ItemList presenter);
Presenter.ItemList getPresenter();
void packItem(com.hikapro.backpack.model.entities.Item item);
void unpackItem(com.hikapro.backpack.model.entities.Item item);
void unpackSet(int setId);
void restoreSet(int setId);
}
interface Detail extends Base {
int getCount();
com.hikapro.backpack.model.entities.Item getCurrentItem();
void setCurrentItem(com.hikapro.backpack.model.entities.Item item);
Bitmap getPicture();
void setPresenter(Presenter.ItemDetail presenter);
Presenter.ItemDetail getPresenter();
void pendingRemove(com.hikapro.backpack.model.entities.Item item);
void pendingRemoveCancel(com.hikapro.backpack.model.entities.Item item);
void packItem(com.hikapro.backpack.model.entities.Item item);
void unpackItem(com.hikapro.backpack.model.entities.Item item);
}
interface Share extends Base {
void setPresenter(Presenter.Share presenter);
Presenter.Share getPresenter();
}
interface Add extends Base {
void setPresenter(Presenter.Add presenter);
Presenter.Add getPresenter();
void filter(String query, int checkThisSet);
int getItemsCount();
com.hikapro.backpack.model.entities.Item getItemByPosition(int position);
int getCategoriesCount();
Category getCategoryByPosition(int position);
Category getCategoryById(int id);
void add(com.hikapro.backpack.model.entities.Item item, int setId);
}
}

View File

@ -0,0 +1,43 @@
package com.hikapro.backpack.model;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import java.net.InetAddress;
/**
* Created by tariel on 29/05/16.
*/
public class NetworkUtil {
public static boolean isConnectedToNetwork(Context context) {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
return isConnected;
}
public static boolean isInternetAvailable() {
boolean ret;
try {
InetAddress ipAddr = InetAddress.getByName("hikapro.com");
ret = ipAddr.equals("") ? false : true;
} catch (Exception e) {
ret = false;
}
return ret;
}
public static int getConnectionType(Context context) {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork.getType();
//ConnectivityManager.TYPE_WIFI;
}
}

View File

@ -0,0 +1,159 @@
package com.hikapro.backpack.model;
import android.os.Message;
import android.widget.Toast;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import com.hikapro.backpack.App;
import com.hikapro.backpack.model.dao.Command;
import com.hikapro.backpack.model.dao.Event;
import com.hikapro.backpack.model.entities.Category;
import com.hikapro.backpack.model.entities.Item;
/**
* Created by tariel on 12/05/16.
*/
public class PackedModel extends ItemModel {
public PackedModel() {
super();
}
@Override
public void executeQuery() {
Message command;
dao.registerObserver(this);
if (categoriesCache.isEmpty()) {
command = Message.obtain();
command.what = Command.ITEM_GET_CATEGORIES;
dao.executeCommand(command);
}
command = Message.obtain();
command.what = Command.SET_GET_PACKED_ITEMS;
command.arg1 = currentSet;
dao.executeCommand(command);
command = Message.obtain();
command.what = Command.SET_GET_STAT;
command.arg1 = presenter.getCurrentSet().getId();
dao.executeCommand(command);
}
@Override
public void filter(String query) {
if (query.isEmpty()) {
Message command = Message.obtain();
command.what = Command.SET_GET_PACKED_ITEMS;
command.arg1 = presenter.getCurrentSet().getId();
dao.executeCommand(command);
} else {
Message command = Message.obtain();
command.what = Command.SET_GET_ITEMS_LIKE_PACKED;
command.arg1 = presenter.getCurrentSet().getId();
command.obj = query;
dao.executeCommand(command);
}
}
@Override
public void onEvent(Message event) {
switch (event.what) {
case Event.SET_PACKED_LOAD_ERROR :
break;
case Event.SET_UNPACK_ERROR :
break;
case Event.SET_GET_STAT_ERROR:
break;
case Event.ITEM_CATEGORY_LOAD_ERROR :
break;
case Event.ITEM_PACK_ERROR :
break;
case Event.ITEM_UNPACK_ERROR :
break;
case Event.ITEM_PENDING_REMOVAL_ERROR:
break;
case Event.ITEM_REMOVAL_CANCEL_ERROR:
break;
case Event.SET_ITEMS_LIKE_PACKED_ERROR:
if (!itemsCache.isEmpty()) {
itemsCache.clear();
}
notifyDataSetChanged();
break;
case Event.SET_PACKED_LOAD_COMPLETED :
itemsCache = (List<Item>) event.obj;
notifyDataSetChanged();
break;
case Event.SET_ITEMS_LIKE_PACKED_COMPLETED:
itemsCache = (List<Item>) event.obj;
notifyDataSetChanged();
break;
case Event.SET_GET_STAT_COMPLETED:
currentSetActiveItemsQty = event.arg1;
packedQty = event.arg2;
if (presenter != null)
presenter.notifyItemPackStatusChanged();
break;
case Event.ITEM_FROM_SET_DELETED:
executeQuery();
break;
case Event.ITEM_PENDING_REMOVAL_COMPLETED:// TODO DEL
executeQuery();
break;
case Event.ITEM_REMOVAL_CANCELED:
executeQuery();
break;
case Event.ITEM_READ_COMPLETED:
itemsCache.add((Item) event.obj);
Collections.sort(itemsCache);
notifyDataSetChanged();
break;
case Event.SET_UNPACK_COMPLETED :
executeQuery();
break;
case Event.ITEM_CATEGORY_LOAD_COMPLETED :
categoriesCache = (Hashtable<Integer, Category>)event.obj;
break;
case Event.ITEM_PACKED :
executeQuery();
break;
case Event.ITEM_UNPACKED :
executeQuery();
break;
case Event.SET_RESTORE_COMPLETED:
executeQuery();
Toast.makeText(App.getAppContext(), "Restore completed", Toast.LENGTH_SHORT).show();
break;
}
}
@Override
public void unpackItem(com.hikapro.backpack.model.entities.Item item) {
if (item != null) {
Message command = Message.obtain();
command.what = Command.ITEM_UNPACK;
command.arg1 = currentSet;
command.arg2 = item.getId();
dao.executeCommand(command);
itemsCache.remove(item); // TODO check nn
}
}
@Override
public void packItem(com.hikapro.backpack.model.entities.Item item) {
if (item != null) {
Message command = Message.obtain();
command.what = Command.ITEM_REMOVAL_CANCEL;
command.arg1 = currentSet;
command.arg2 = item.getId();
dao.executeCommand(command);
itemsCache.remove(item);
}
}
}

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.model;
package com.hikapro.backpack.model;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

View File

@ -1,15 +1,18 @@
package hikapro.com.backpack.model;
package com.hikapro.backpack.model;
import android.os.Message;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import hikapro.com.backpack.model.dao.Command;
import hikapro.com.backpack.model.dao.DAO;
import hikapro.com.backpack.model.dao.Event;
import hikapro.com.backpack.model.entities.Set;
import hikapro.com.backpack.presenter.Presenter;
import com.hikapro.backpack.App;
import com.hikapro.backpack.R;
import com.hikapro.backpack.model.dao.Command;
import com.hikapro.backpack.model.dao.DAO;
import com.hikapro.backpack.model.dao.Event;
import com.hikapro.backpack.model.entities.Set;
import com.hikapro.backpack.presenter.Presenter;
/**
@ -17,7 +20,7 @@ import hikapro.com.backpack.presenter.Presenter;
*/
public class SetModel implements Model.Set {
private List<hikapro.com.backpack.model.entities.Set> cache;
private List<com.hikapro.backpack.model.entities.Set> cache;
private Presenter.SetList presenter;
private DAO dao;
@ -31,11 +34,11 @@ public class SetModel implements Model.Set {
//region sets
@Override
public hikapro.com.backpack.model.entities.Set getSetByPosition(int position) {
public com.hikapro.backpack.model.entities.Set getSetByPosition(int position) {
return cache.get(position);
}
@Override
public hikapro.com.backpack.model.entities.Set findSet(int id) {
public com.hikapro.backpack.model.entities.Set findSet(int id) {
Set ret = null;
for (Set s : cache) {
if (s.getId() == id) {
@ -67,18 +70,16 @@ public class SetModel implements Model.Set {
}
private void sendMessage(String message) {
presenter.showMessage(message);
}
//endregion
//region process
@Override
public void executeQuery() {
if (presenter != null)
presenter.startProgress();
Message command = Message.obtain();
command.what = Command.SYNC_IF_NOT_EXISTS;
command.what = Command.SYNC;
dao.executeCommand(command);
command = Message.obtain();
command.what = Command.SET_GET_ALL;
@ -88,13 +89,33 @@ public class SetModel implements Model.Set {
@Override
public void onEvent(Message event) {
switch (event.what) {
case Event.SYNC_NO_CONNECTION :
if (presenter != null)
presenter.stopProgress();
Toast.makeText(App.getAppContext(), R.string.no_connection, Toast.LENGTH_SHORT).show();
Message command = Message.obtain();
command.what = Command.SYNC_READ_FROM_FILE;
dao.executeCommand(command);
command = Message.obtain();
command.what = Command.SET_GET_ALL;
dao.executeCommand(command);
break;
case Event.SYNC_FAILED :
if (presenter != null)
presenter.stopProgress();
Toast.makeText(App.getAppContext(), "SYNC FAILED", Toast.LENGTH_SHORT).show();
break;
case Event.SET_LOAD_ERROR :
if (presenter != null)
presenter.stopProgress();
break;
case Event.SET_ITEMS_LOAD_ERROR :
break;
case Event.SET_REORDER_ERROR :
break;
case Event.SET_LOAD_COMPLETED :
if (presenter != null)
presenter.stopProgress();
cache = (List<Set>) event.obj;
notifyDataSetChanged();
break;
@ -135,7 +156,7 @@ public class SetModel implements Model.Set {
//GLM
@Override
public List<hikapro.com.backpack.model.entities.Set> getSets()
public List<com.hikapro.backpack.model.entities.Set> getSets()
{
return cache;
}

View File

@ -0,0 +1,50 @@
package com.hikapro.backpack.model;
import android.os.Message;
import com.hikapro.backpack.model.dao.DAO;
import com.hikapro.backpack.presenter.Presenter;
/**
* Created by tariel on 16/05/16.
*/
public class ShareModel implements Model.Share {
private Presenter.Share presenter;
private DAO dao;
public ShareModel() {
this.dao = DAO.getInstance();
dao.registerObserver(this);
}
@Override
public void onDestroy(boolean isConfigurationChanging) {
}
@Override
public void executeQuery() {
}
@Override
public void notifyDataSetChanged() {
}
@Override
public void onEvent(Message event) {
}
@Override
public void setPresenter(Presenter.Share presenter) {
this.presenter = presenter;
}
@Override
public Presenter.Share getPresenter() {
return presenter;
}
}

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.model.dao;
package com.hikapro.backpack.model.dao;
/**
* Created by tariel on 27/04/16.
@ -15,6 +15,11 @@ public interface Command {
int SET_GET_ITEMS = 0x66;
int SET_GET_PACKED_ITEMS = 0x67;
int SET_UNPACK_ITEMS = 0x68;
int SET_RESTORE_DEFAULT = 0x69;
int SET_GET_STAT = 0x70;
int SET_CLEAN_PACKED = 0x71;
int SET_GET_ITEMS_LIKE = 0x72;
int SET_GET_ITEMS_LIKE_PACKED = 0x73;
int ITEM_DELETE_FROM_SET = 0x78;
int ITEM_INSERT = 0x79;
@ -22,6 +27,10 @@ public interface Command {
int ITEM_UNPACK = 0x7B;
int ITEM_GET_CATEGORIES = 0x7C;
int ITEM_GET_IMAGE = 0x7D;
int ITEM_GET_LIKE = 0x7E;
int ITEM_PENDING_REMOVAL = 0x7F;
int ITEM_REMOVAL_CANCEL = 0x80;
int ITEM_READ = 0x81;
int MY_LIST_POST = 0x8C;
int MY_LIST_ITEM_ADD = 0x8D;
@ -30,6 +39,7 @@ public interface Command {
int SYNC = 0xA0;
int SYNC_IF_NOT_EXISTS = 0xA1;
int SYNC_READ_FROM_FILE = 0xA2;
int TEST = 0xC8;

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.model.dao;
package com.hikapro.backpack.model.dao;
import android.content.ContentValues;
import android.database.Cursor;
@ -8,12 +8,13 @@ import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Locale;
import hikapro.com.backpack.model.entities.Category;
import hikapro.com.backpack.model.entities.Item;
import hikapro.com.backpack.model.entities.Set;
import hikapro.com.backpack.model.entities.Timestamp;
import hikapro.com.backpack.model.entities.UpdateLog;
import com.hikapro.backpack.model.entities.Category;
import com.hikapro.backpack.model.entities.Item;
import com.hikapro.backpack.model.entities.Set;
import com.hikapro.backpack.model.entities.Timestamp;
import com.hikapro.backpack.model.entities.UpdateLog;
/**
* Created by tariel on 20/04/16.
@ -64,6 +65,7 @@ public class Db {
public static final String COLUMN_PHOTO_THUMB_URL = "photo_thumb_url";
public static final String COLUMN_PHOTO_LOCAL = "photo_local";
public static final String COLUMN_PHOTO_THUMB_LOCAL = "photo_thumb_local";
public static final String COLUMN_USER_DEFINED = "user_defined";
public static final String CREATE =
@ -76,6 +78,7 @@ public class Db {
COLUMN_PHOTO_URL + " TEXT, " +
COLUMN_PHOTO_THUMB_URL + " TEXT, " +
COLUMN_PHOTO_LOCAL + " TEXT, " +
COLUMN_USER_DEFINED + " NUMERIC, " +
COLUMN_PHOTO_THUMB_LOCAL + " TEXT" +
" ); ";
@ -98,6 +101,8 @@ public class Db {
values.put(COLUMN_PHOTO_THUMB_URL, item.getPhotoThumbUrl());
if (item.getPhotoLocal() != null)
values.put(COLUMN_PHOTO_LOCAL, item.getPhotoLocal());
values.put(COLUMN_USER_DEFINED, item.isUserDefined());
/*
values.put(COLUMN_PHOTO_THUMB_LOCAL, item.getName());
*/
@ -122,6 +127,18 @@ public class Db {
item.setPhotoUrl(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_PHOTO_URL)));
item.setPhotoThumbUrl(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_PHOTO_THUMB_URL)));
item.setPhotoLocal(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_PHOTO_LOCAL)));
short buf = cursor.getShort(cursor.getColumnIndexOrThrow(COLUMN_USER_DEFINED));
item.setUserDefined(buf != 0);
int check = cursor.getColumnIndex(SetItemsTable.COLUMN_PENDING_REMOVAL);
if (check != -1) {
buf = cursor.getShort(check);
item.setPendingRemoval(buf != 0);
}
check = cursor.getColumnIndex(SetItemsTable.COLUMN_PACKED);
if (check != -1) {
buf = cursor.getShort(check);
item.setPacked(buf != 0);
}
return item;
}
@ -215,11 +232,13 @@ public class Db {
public static final String COLUMN_ID = "_id";
public static final String COLUMN_MODIFIED_DATETIME = "modified_datetime";
public static final String COLUMN_TIMESTAMP = "timestamp";
public static final String COLUMN_LOCALE = "locale";
public static final String CREATE =
"CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_TIMESTAMP + " INTEGER NOT NULL, " +
COLUMN_LOCALE + " TEXT, " +
COLUMN_MODIFIED_DATETIME + " INTEGER NOT NULL DEFAULT current_timestamp" +
" ); ";
@ -227,13 +246,16 @@ public class Db {
ContentValues values = new ContentValues();
values.put(COLUMN_TIMESTAMP, timestamp.timestamp);
values.put(COLUMN_LOCALE, Locale.getDefault().getLanguage());
return values;
}
public static UpdateLog parseCursor(Cursor cursor) {
UpdateLog log = new UpdateLog();
log.setId(cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_ID)));
log.setTimestamp(cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_TIMESTAMP)));
log.setModifiedDatetime(cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_MODIFIED_DATETIME)));
log.setLocale(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_LOCALE)));
return log;
}
}
@ -246,14 +268,18 @@ public class Db {
public static final String COLUMN_SET = "setId";
public static final String COLUMN_ITEM = "itemId";
public static final String COLUMN_DELETED = "deleted";
public static final String COLUMN_PENDING_REMOVAL = "pending_removal";
public static final String COLUMN_PACKED = "packed";
public static final String COLUMN_USER_DEFINED = "user_defined";
public static final String CREATE =
"CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_SET + " INTEGER NOT NULL, " +
COLUMN_DELETED + " NUMERIC, " +
COLUMN_PENDING_REMOVAL + " NUMERIC, " +
COLUMN_PACKED + " NUMERIC, " +
COLUMN_USER_DEFINED + " NUMERIC, " +
COLUMN_ITEM + " INTEGER NOT NULL" +
" ); ";
@ -262,7 +288,20 @@ public class Db {
values.put(COLUMN_SET, setId);
values.put(COLUMN_ITEM, itemId);
values.put(COLUMN_DELETED, 0);
values.put(COLUMN_PENDING_REMOVAL, 0);
values.put(COLUMN_PACKED, 0);
values.put(COLUMN_USER_DEFINED, 0);
return values;
}
public static ContentValues toContentValues(int setId, int itemId, boolean userDefined) {
ContentValues values = new ContentValues();
values.put(COLUMN_SET, setId);
values.put(COLUMN_ITEM, itemId);
values.put(COLUMN_DELETED, 0);
values.put(COLUMN_PENDING_REMOVAL, 0);
values.put(COLUMN_PACKED, 0);
values.put(COLUMN_USER_DEFINED, userDefined);
return values;
}
}

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.model.dao;
package com.hikapro.backpack.model.dao;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

View File

@ -1,19 +1,20 @@
package hikapro.com.backpack.model.dao;
package com.hikapro.backpack.model.dao;
/**
* Created by tariel on 27/04/16.
*/
public interface Event {
int SET_SCOPE_END = 0x13;
int ITEM_SCOPE_END = 0x27;
int MY_LIST_SCOPE_END = 0x3B;
int SET_LOAD_ERROR = -0x1;
int SET_REORDER_ERROR = -0x2;
int SET_ITEMS_LOAD_ERROR = -0x3;
int SET_PACKED_LOAD_ERROR = -0x4;
int SET_UNPACK_ERROR = -0x5;
int SET_RESTORE_ERROR = -0x6;
int SET_GET_STAT_ERROR = -0x7;
int SET_CLEAN_PACKED_ERROR = -0x8;
int SET_ITEMS_LIKE_ERROR = -0x9;
int SET_ITEMS_LIKE_PACKED_ERROR = -0xA;
int SET_LOAD_COMPLETED = 0x1;
@ -21,7 +22,11 @@ public interface Event {
int SET_ITEMS_LOAD_COMPLETED = 0x3;
int SET_PACKED_LOAD_COMPLETED = 0x4;
int SET_UNPACK_COMPLETED = 0x5;
int SET_RESTORE_COMPLETED = 0x6;
int SET_GET_STAT_COMPLETED = 0x7;
int SET_PACKED_CLEANED = 0x8;
int SET_ITEMS_LIKE_COMPLETED = 0x9;
int SET_ITEMS_LIKE_PACKED_COMPLETED = 0xA;
int ITEM_FROM_SET_ERROR = -0x14;
int ITEM_INSERT_ERROR = -0x15;
@ -30,6 +35,10 @@ public interface Event {
int ITEM_UNPACK_ERROR = -0x18;
int ITEM_CATEGORY_LOAD_ERROR = -0x19;
int ITEM_IMAGE_LOAD_ERROR = -0x1A;
int ITEM_LIKE_LOAD_ERROR = -0x1B;
int ITEM_PENDING_REMOVAL_ERROR = -0x1C;
int ITEM_REMOVAL_CANCEL_ERROR = -0x1D;
int ITEM_READ_ERROR = -0x1E;
int ITEM_FROM_SET_DELETED = 0x14;
int ITEM_INSERTED = 0x15;
@ -38,7 +47,10 @@ public interface Event {
int ITEM_UNPACKED = 0x18;
int ITEM_CATEGORY_LOAD_COMPLETED = 0x19;
int ITEM_IMAGE_LOAD_COMPLETED = 0x1A;
int ITEM_LIKE_LOAD_COMPLETED = 0x1B;
int ITEM_PENDING_REMOVAL_COMPLETED = 0x1C;
int ITEM_REMOVAL_CANCELED = 0x1D;
int ITEM_READ_COMPLETED = 0x1E;
int MY_LIST_POST_ERROR = -0x28;
int MY_LIST_ITEM_ADD_ERROR = -0x29;
@ -51,6 +63,7 @@ public interface Event {
int MY_LIST_CLEARED = 0x2B;
int SYNC_FAILED = -0x3C;
int SYNC_NO_CONNECTION = -0x3D;
int SYNC_COMPLETED = 0x3C;
int NOT_IMPLEMENTED = 0x50;

View File

@ -1,26 +1,29 @@
package hikapro.com.backpack.model.dao;
package com.hikapro.backpack.model.dao;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import hikapro.com.backpack.App;
import com.hikapro.backpack.App;
/**
* Created by tariel on 04/05/16.
*/
public class ImageDownloadHelper {
public static final String ITEMS_TAG = "items";
public static final String IMAGE_DOWNLOAD_TAG = "Image download";
public static final String IMAGE_DIRECTORY_NAME = "items";
private Context context;
public ImageDownloadHelper() {
@ -32,10 +35,15 @@ public class ImageDownloadHelper {
try {
URL url = new URL(netPath);
URLConnection conn = url.openConnection();
conn.setReadTimeout(4000);
bitmap = BitmapFactory.decodeStream(conn.getInputStream());
} catch (SocketTimeoutException ex) {
bitmap = null;
Log.e(IMAGE_DOWNLOAD_TAG, " Timeout elapsed.");
} catch (Exception ex) {
Log.e(ITEMS_TAG, " File cannot be downloaded");
Log.e(IMAGE_DOWNLOAD_TAG, " File cannot be downloaded due to exception.");
}
return bitmap;
}
@ -62,8 +70,9 @@ public class ImageDownloadHelper {
try {
file = File.createTempFile(fileName, null, context.getCacheDir());
} catch (IOException e) {
Log.e(ITEMS_TAG, " Cannot obtain temp file");
Log.e(IMAGE_DOWNLOAD_TAG, " Cannot obtain temp file");
}
return file;
}
@ -77,17 +86,25 @@ public class ImageDownloadHelper {
public String saveImageInternal(String filename, Bitmap bitmap) {
File file = null;
FileOutputStream outputStream;
FileOutputStream outputStream = null;
if (bitmap != null && !filename.isEmpty()) {
file = createTempFile(filename);
if (file != null) {
try {
outputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
Log.e(ITEMS_TAG, " File cannot be saved");
Log.e(IMAGE_DOWNLOAD_TAG, "File cannot be saved (Internal): " + e);
} finally {
if (outputStream != null) {
try {
outputStream.flush();
outputStream.close();
} catch (IOException e) {
// do nothing here
}
}
}
}
}
@ -96,18 +113,32 @@ public class ImageDownloadHelper {
public String saveImageExternal(String filename, Bitmap bitmap) {
File file = null;
FileOutputStream outputStream;
FileOutputStream outputStream = null;
if (isExternalStorageWritable()) {
if (bitmap != null && !filename.isEmpty()) {
File directory = getDir();
file = new File(directory.getAbsoluteFile(), filename);
try {
outputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
outputStream.flush();
outputStream.close();
File directory = getDir();
if (directory != null) {
file = new File(directory.getAbsoluteFile(), filename);
outputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
} else {
Log.e(IMAGE_DOWNLOAD_TAG, "Saving failed (External): directory unavailable.");
}
} catch (Exception e) {
Log.e(ITEMS_TAG, " File cannot be saved");
Log.e(IMAGE_DOWNLOAD_TAG, "File cannot be saved (External): " + e);
} finally {
if (outputStream != null) {
try {
outputStream.flush();
outputStream.close();
} catch (IOException e) {
// do nothing here
}
}
}
}
}
@ -116,30 +147,47 @@ public class ImageDownloadHelper {
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
boolean ret;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
ret = true;
} else
ret = false;
return ret;
}
/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
boolean ret;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
ret = true;
} else
ret = false;
return ret;
}
private File getDir() {
// Get the directory for the app's private pictures directory.
File file = new File(context.getExternalFilesDir(
Environment.DIRECTORY_PICTURES), ITEMS_TAG);
if (!file.mkdirs()) {
Log.e(ITEMS_TAG, " Directory not created");
File ret = null;
// Get available SD cards
File[] dirs = ContextCompat.getExternalFilesDirs(context, Environment.DIRECTORY_PICTURES);
if (dirs != null) {
switch (dirs.length) {
case 1:
ret = new File(dirs[0], IMAGE_DIRECTORY_NAME); // can be emulated SD card
break;
case 2:
ret = new File(dirs[1], IMAGE_DIRECTORY_NAME);// real SD card
break;
}
}
return file;
if (!ret.mkdirs()) {
Log.e(IMAGE_DOWNLOAD_TAG, "Directory was not created or already exists.");
}
return ret;
}
}

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.model.dao;
package com.hikapro.backpack.model.dao;
/**
* Created by tariel on 27/04/16.

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.model.entities;
package com.hikapro.backpack.model.entities;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.model.entities;
package com.hikapro.backpack.model.entities;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
@ -36,9 +36,23 @@ public class Item implements Comparable<Item>, Serializable {
private String photoLocal;
private boolean userDefined;
private boolean pendingRemoval;
private boolean packed;
public boolean InList;
public Item() {
}
public Item(String name, int category) {
this.id = -1;
this.name = name;
this.category = category;
}
public Item(int id, String name, int category, String description, List<String> buyUrls,
String photoUrl, String photoThumbUrl) {
this.id = id;
@ -114,6 +128,30 @@ public class Item implements Comparable<Item>, Serializable {
this.photoLocal = photoLocal;
}
public boolean isUserDefined() {
return userDefined;
}
public void setUserDefined(boolean userDefined) {
this.userDefined = userDefined;
}
public boolean isPendingRemoval() {
return pendingRemoval;
}
public void setPendingRemoval(boolean pendingRemoval) {
this.pendingRemoval = pendingRemoval;
}
public boolean isPacked() {
return packed;
}
public void setPacked(boolean packed) {
this.packed = packed;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
@ -136,7 +174,16 @@ public class Item implements Comparable<Item>, Serializable {
@Override
public int compareTo(Item another) {
/*
int cmp = Integer.valueOf(category).compareTo(Integer.valueOf(another.category));
return (cmp != 0 ? cmp : name.compareTo(another.name));
*/
int cmp = Integer.valueOf(category).compareTo(Integer.valueOf(another.category));
if (cmp != 0)
return cmp;
else {
cmp = Boolean.valueOf(pendingRemoval).compareTo(Boolean.valueOf(another.pendingRemoval));
return (cmp != 0 ? cmp : name.compareTo(another.name));
}
}
}

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.model.entities;
package com.hikapro.backpack.model.entities;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.model.entities;
package com.hikapro.backpack.model.entities;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
@ -15,6 +15,10 @@ public class Timestamp {
public Timestamp() {
}
public Timestamp(long value) {
this.timestamp = value;
}
}

View File

@ -1,16 +1,26 @@
package hikapro.com.backpack.model.entities;
package com.hikapro.backpack.model.entities;
/**
* Created by tariel on 27/04/16.
*/
public class UpdateLog {
private int id;
private long timestamp;
private long modifiedDatetime;
private String locale;
public UpdateLog() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public long getTimestamp() {
return timestamp;
}
@ -26,4 +36,12 @@ public class UpdateLog {
public void setModifiedDatetime(long modifiedDatetime) {
this.modifiedDatetime = modifiedDatetime;
}
public String getLocale() {
return locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
}

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.model.entities;
package com.hikapro.backpack.model.entities;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

View File

@ -0,0 +1,335 @@
package com.hikapro.backpack.presenter;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SearchView;
import android.widget.Toast;
import com.hikapro.backpack.R;
import com.hikapro.backpack.model.Model;
import com.hikapro.backpack.model.entities.Category;
import com.hikapro.backpack.model.entities.Item;
import com.hikapro.backpack.presenter.adapters.AddListAdapter;
import com.hikapro.backpack.presenter.adapters.helper.FlowLayout;
import com.hikapro.backpack.presenter.adapters.helper.Util;
import com.hikapro.backpack.presenter.adapters.helper.items.DividerDecoration;
import com.hikapro.backpack.presenter.adapters.helper.items.DividerDecoration2;
import com.hikapro.backpack.view.View;
import java.lang.ref.WeakReference;
/**
* Created by tariel on 18/05/16.
*/
public class AddPresenter implements Presenter.Add {
private WeakReference<View.Add> view;
private Model.Add model;
private AddListAdapter adapter;
private RecyclerView recycler;
private FlowLayout categoryContainer;
private ViewGroup categoryContainerMain;
private boolean isContainerAlreadyInitialised;
private Item newItem;
private Item selectedItem;
private Button currentCategoryButton;
private Button cancelButton;
private Button saveButton;
private SearchView searchView;
private boolean canSave;
public AddPresenter() {
this.adapter = new AddListAdapter(this);
}
@Override
public void setView(View.Add view) {
this.view = new WeakReference<>(view);
}
@Override
public void setModel(Model.Add model) {
this.model = model;
}
@Override
public Model.Add getModel() {
return model;
}
@Override
public void onDestroy(boolean isChangingConfiguration) {
view = null;
model.onDestroy(isChangingConfiguration);
if ( !isChangingConfiguration ) {
model = null;
}
isContainerAlreadyInitialised = false;
}
@Override
public android.view.View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
android.view.View view = inflater.inflate(R.layout.fragment_add, container, false);
model.executeQuery();
LinearLayoutManager llm = new LinearLayoutManager(getActivityContext());
recycler = (RecyclerView) view.findViewById(R.id.add_item_recycler);
recycler.setLayoutManager(llm);
recycler.setAdapter(adapter);
recycler.setItemAnimator(new DefaultItemAnimator());
//recycler.addItemDecoration(new DividerDecoration(getActivityContext()));
recycler.addItemDecoration(new DividerDecoration2(getActivityContext(), R.drawable.divider2, Util.dp2px(getAppContext(), 16)));
categoryContainer = (FlowLayout) view.findViewById(R.id.add_item_category_flow);
//categoryContainer.setPaddings(Util.dp2px(getAppContext(), 15), Util.dp2px(getAppContext(), 15)); // TODO check here
categoryContainerMain = (ViewGroup) view.findViewById(R.id.add_item_category_container);
categoryContainerMain.setVisibility(android.view.View.GONE);
recycler.setVisibility(android.view.View.GONE);
Activity activity = (Activity) getActivityContext();
if (activity != null) {
ActionBar actionBar = activity.getActionBar();
if (actionBar != null) {
ViewGroup custActionBarView = (ViewGroup) inflater.inflate(R.layout.add_cust_actionbar, null);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setCustomView(custActionBarView);
cancelButton = (Button) custActionBarView.findViewById(R.id.action_add_cancel);
saveButton = (Button) custActionBarView.findViewById(R.id.action_add_save);
cancelButton.setOnClickListener(new ActionBarButtonClickListener());
saveButton.setOnClickListener(new ActionBarButtonClickListener());
}
}
searchView = (SearchView) view.findViewById(R.id.add_search);
searchView.setIconified(false);
searchView.setIconifiedByDefault(false);
searchView.setQueryHint("Enter a new item name");
searchView.setSubmitButtonEnabled(false);
searchView.setBottom(20);
/*
Drawable d = getActivityContext().getResources().getDrawable( R.drawable.search_divider );
searchView.setDividerDrawable(d);*/
int magId = searchView.getContext().getResources().getIdentifier("android:id/search_mag_icon", null, null);
ImageView magImage = (ImageView) searchView.findViewById(magId);
magImage.setLayoutParams(new LinearLayout.LayoutParams(0, 0));
searchView.setMinimumHeight(40);
searchView.setOnQueryTextListener(new SearchTextListener());
/*
int searchPlateId = searchView.getContext().getResources().getIdentifier("android:id/search_plate", null, null);
// Getting the 'search_plate' LinearLayout.
android.view.View searchPlate = searchView.findViewById(searchPlateId);
// Setting background of 'search_plate' to earlier defined drawable.
searchPlate.setBackgroundResource(R.drawable.search_divider);
*/
return view;
}
@Override
public Context getAppContext() {
try {
return getView().getAppContext();
} catch (NullPointerException e) {
return null;
}
}
@Override
public Context getActivityContext() {
try {
return getView().getActivityContext();
} catch (NullPointerException e) {
return null;
}
}
@Override
public void notifyDataSetChanged(boolean found) {
adapter.notifyDataSetChanged();
if (found) {
categoryContainerMain.setVisibility(android.view.View.GONE);
recycler.setVisibility(android.view.View.VISIBLE);
currentCategoryButton = null;
} else {
categoryContainerMain.setVisibility(android.view.View.VISIBLE);
recycler.setVisibility(android.view.View.GONE);
initSelectCategoryContainer();
}
}
@Override
public void onAddItemClick(Item item) {
searchView.setQuery(item.getName(), false);
if (!item.InList)
selectedItem = item;
setSaveButtonAccess();
}
private void setSaveButtonAccess() {
if (searchView.getQuery().length() > 0 && currentCategoryButton != null
|| selectedItem != null)
canSave = true;
else
canSave = false;
if (canSave)
saveButton.setTextColor(saveButton.getResources().getColor(R.color.save_green));
else
saveButton.setTextColor(saveButton.getResources().getColor(R.color.white));
}
private boolean checkUserInput() {
if (!canSave) {
if (searchView.getQuery().length() == 0)
Toast.makeText(getActivityContext(), "Please, enter a name", Toast.LENGTH_SHORT).show();
else if (categoryContainerMain.getVisibility() == android.view.View.VISIBLE)
Toast.makeText(getActivityContext(), "Please, select a category", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getActivityContext(), "Already in List!", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
private void initSelectCategoryContainer() {
Button button;
Category category;
if (! isContainerAlreadyInitialised) {
for (int i = 0; i < model.getCategoriesCount(); ++i) {
category = model.getCategoryByPosition(i);
button = (Button) LayoutInflater.from(getActivityContext()).inflate(
R.layout.category_button, null);
button.setId(category.getId());
String txt = category.getName();
button.setText(txt);
button.setOnClickListener(new CategoryButtonClickListener());
categoryContainer.addView(button);
if (currentCategoryButton != null) {
if (button.getId() == currentCategoryButton.getId()) {
currentCategoryButton = button;
Drawable d = currentCategoryButton.getBackground();
PorterDuffColorFilter filter = new PorterDuffColorFilter(Color.GREEN, PorterDuff.Mode.SRC_ATOP);
d.setColorFilter(filter);
}
}
}
setSaveButtonAccess();
isContainerAlreadyInitialised = true;
}
}
private View.Add getView() throws NullPointerException {
if ( view != null )
return view.get();
else
throw new NullPointerException("View is unavailable");
}
private class CategoryButtonClickListener implements android.view.View.OnClickListener {
@Override
public void onClick(android.view.View v) {
Drawable d = v.getBackground();
PorterDuffColorFilter filter = new PorterDuffColorFilter(Color.GREEN, PorterDuff.Mode.SRC_ATOP);
d.setColorFilter(filter);
if (currentCategoryButton != null) {
d = currentCategoryButton.getBackground();
currentCategoryButton.invalidateDrawable(d);
d.clearColorFilter();
}
currentCategoryButton = (Button) v;
Toast.makeText(getActivityContext(), "Id " + currentCategoryButton.getId(), Toast.LENGTH_SHORT).show();
setSaveButtonAccess();
}
}
private class ActionBarButtonClickListener implements android.view.View.OnClickListener {
@Override
public void onClick(android.view.View v) {
Fragment fragment = (Fragment) getView();
switch (v.getId())
{
case R.id.action_add_cancel :
Toast.makeText(getActivityContext(), "Cancel", Toast.LENGTH_SHORT).show();
searchView.clearFocus();
if (fragment != null)
fragment.getFragmentManager().popBackStack();
break;
case R.id.action_add_save :
if (checkUserInput()) {
if (selectedItem != null) {
model.add(selectedItem, getView().getSet().getId());
} else {
newItem = new Item(searchView.getQuery().toString(), currentCategoryButton.getId());
newItem.setUserDefined(true);
model.add(newItem, getView().getSet().getId());
}
searchView.clearFocus();
if (fragment != null)
fragment.getFragmentManager().popBackStack();
}
break;
}
}
}
private class SearchTextListener implements SearchView.OnQueryTextListener {
public SearchTextListener() {
super();
}
@Override
public boolean onQueryTextChange(String newText) {
model.filter(newText, getView().getSet().getId());
if (newText.isEmpty()) {
if (currentCategoryButton != null) {
Drawable d = currentCategoryButton.getBackground();
currentCategoryButton.invalidateDrawable(d);
d.clearColorFilter();
currentCategoryButton = null;
}
}
selectedItem = null;
setSaveButtonAccess();
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
}
}

View File

@ -0,0 +1,247 @@
package com.hikapro.backpack.presenter;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.webkit.URLUtil;
import android.widget.ImageView;
import android.widget.TextView;
import java.lang.ref.WeakReference;
import com.hikapro.backpack.R;
import com.hikapro.backpack.model.Model;
import com.hikapro.backpack.model.entities.Item;
import com.hikapro.backpack.presenter.adapters.ItemDetailAdapter;
import com.hikapro.backpack.presenter.adapters.helper.OnSwipeTouchListener;
import com.hikapro.backpack.presenter.adapters.helper.Util;
import com.hikapro.backpack.presenter.adapters.helper.items.DividerDecoration;
import com.hikapro.backpack.presenter.adapters.helper.items.DividerDecoration2;
import com.hikapro.backpack.view.View;
/**
* Created by tariel on 23/04/16.
*/
public class ItemDetailPresenter implements Presenter.ItemDetail {
private WeakReference<View.ItemDetail> view;
private Model.Detail model;
private Model.Item exModel;
private ItemDetailAdapter adapter;
private Item item;
private int setId;
private ImageView itemPhoto;
private TextView itemDescription;
private TextView itemLink;
private int position;
private ViewGroup progress;
private OnSwipeTouchListener swipeTouchListener;
public ItemDetailPresenter(Model.Item itemModel, int startPosition) {
this.adapter = new ItemDetailAdapter(this);
this.exModel = itemModel;
this.position = startPosition;
}
@Override
public void onDestroy(boolean isChangingConfiguration) {
view = null;
model.onDestroy(isChangingConfiguration);
if ( !isChangingConfiguration ) {
model = null;
}
}
@Override
public android.view.View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
android.view.View view = inflater.inflate(R.layout.fragment_item_detail, container, false);
itemPhoto = (ImageView) view.findViewById(R.id.item_photo);
itemDescription = (TextView) view.findViewById(R.id.item_description);
itemLink = (TextView) view.findViewById(R.id.item_link);
progress = (ViewGroup) view.findViewById(R.id.detail_progress_container);
progress.setVisibility(android.view.View.VISIBLE);
swipeTouchListener = new OnSwipeTouchListener(getActivityContext()) {
@Override
public void onSwipeLeft() {
swipeLeft();
}
@Override
public void onSwipeRight() {
swipeRight();
}
};
progress.setOnTouchListener(swipeTouchListener);
itemDescription.setOnTouchListener(swipeTouchListener);
LinearLayoutManager llm = new LinearLayoutManager(getActivityContext());
RecyclerView detailRecycler = (RecyclerView) view.findViewById(R.id.item_detail_recycler);
detailRecycler.setLayoutManager(llm);
detailRecycler.setAdapter(adapter);
detailRecycler.setItemAnimator(new DefaultItemAnimator());
//detailRecycler.addItemDecoration(new DividerDecoration(getActivityContext()));
detailRecycler.addItemDecoration(new DividerDecoration2(getActivityContext(), R.drawable.divider, Util.dp2px(getAppContext(), 16)));
detailRecycler.setHasFixedSize(true);
model.setCurrentItem(exModel.getItemByPosition(position));
model.executeQuery();
Activity activity = (Activity) getActivityContext();
if (activity != null) {
activity.invalidateOptionsMenu();
ActionBar actionBar = activity.getActionBar();
if (actionBar != null) {
actionBar.show();
actionBar.setTitle(R.string.what_is_it);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setDisplayShowCustomEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
return view;
}
@Override
public void onSaveInstanceState(Bundle outState) {
}
@Override
public void notifyDataSetChanged() {
adapter.notifyDataSetChanged();
item = model.getCurrentItem();
if (!TextUtils.isEmpty(item.getDescription())) {
itemDescription.setText(item.getDescription());
itemDescription.setVisibility(android.view.View.VISIBLE);
} else {
itemDescription.setVisibility(android.view.View.GONE);
}
if (item.getBuyUrls() != null && !item.getBuyUrls().isEmpty()) {
itemLink.setVisibility(android.view.View.VISIBLE);
itemLink.setOnClickListener(new android.view.View.OnClickListener() {
@Override
public void onClick(android.view.View v) {
if (URLUtil.isValidUrl(item.getBuyUrls().get(0))) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(item.getBuyUrls().get(0)));
Activity activity = (Activity) getActivityContext();
if (activity != null) {
if (browserIntent.resolveActivity(activity.getPackageManager()) != null)
activity.startActivity(browserIntent);
}
}
}
});
} else {
itemLink.setVisibility(android.view.View.GONE);
itemLink.setOnClickListener(null);
}
}
@Override
public void setView(View.ItemDetail view) {
this.view = new WeakReference<>(view);
this.setId = view.getSetId();
}
@Override
public void setModel(Model.Detail model) {
this.model = model;
}
@Override
public Model.Detail getModel() {
return model;
}
@Override
public Item getCurrentItem() {
return item;
}
@Override
public Context getAppContext() {
try {
return getView().getAppContext();
} catch (NullPointerException e) {
return null;
}
}
@Override
public Context getActivityContext() {
try {
return getView().getActivityContext();
} catch (NullPointerException e) {
return null;
}
}
@Override
public void notifyPictureChanged() {
progress.setVisibility(android.view.View.GONE);
if (model.getPicture() != null) {
itemPhoto.setImageBitmap(model.getPicture());
itemPhoto.setVisibility(android.view.View.VISIBLE);
itemPhoto.setOnTouchListener(swipeTouchListener);
} else {
itemPhoto.setImageBitmap(null);
itemPhoto.setVisibility(android.view.View.GONE);
}
}
private View.ItemDetail getView() throws NullPointerException {
if ( view != null )
return view.get();
else
throw new NullPointerException("View is unavailable");
}
public int getSetId() {
return setId;
}
private boolean isValidPosition(int position) {
boolean ret;
ret = position > -1 && position < exModel.getItemsCount();
return ret;
}
private void swipeLeft() {
if (isValidPosition(position + 1)) {
// start progress
progress.setVisibility(android.view.View.VISIBLE);
itemPhoto.setVisibility(android.view.View.GONE);
// load data
model.setCurrentItem(exModel.getItemByPosition(++position));
model.executeQuery();
itemPhoto.setImageBitmap(null);
}
}
private void swipeRight() {
if (isValidPosition(position - 1)) {
// start progress
progress.setVisibility(android.view.View.VISIBLE);
itemPhoto.setVisibility(android.view.View.GONE);
// load data
model.setCurrentItem(exModel.getItemByPosition(--position));
model.executeQuery();
itemPhoto.setImageBitmap(null);
}
}
}

View File

@ -1,8 +1,10 @@
package hikapro.com.backpack.presenter;
package com.hikapro.backpack.presenter;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
@ -15,15 +17,17 @@ import android.widget.Toast;
import java.lang.ref.WeakReference;
import hikapro.com.backpack.R;
import hikapro.com.backpack.model.Model;
import hikapro.com.backpack.model.entities.Item;
import hikapro.com.backpack.model.entities.Set;
import hikapro.com.backpack.presenter.adapters.helper.items.DividerDecoration;
import hikapro.com.backpack.presenter.adapters.ItemListAdapter;
import hikapro.com.backpack.presenter.adapters.helper.items.ItemSwipeCallback;
import hikapro.com.backpack.presenter.adapters.helper.items.StickyHeaderDecoration;
import hikapro.com.backpack.view.View;
import com.hikapro.backpack.R;
import com.hikapro.backpack.model.Model;
import com.hikapro.backpack.model.entities.Item;
import com.hikapro.backpack.model.entities.Set;
import com.hikapro.backpack.presenter.adapters.helper.Util;
import com.hikapro.backpack.presenter.adapters.helper.items.DividerDecoration;
import com.hikapro.backpack.presenter.adapters.ItemListAdapter;
import com.hikapro.backpack.presenter.adapters.helper.items.DividerDecoration2;
import com.hikapro.backpack.presenter.adapters.helper.items.ItemSwipeCallback;
import com.hikapro.backpack.presenter.adapters.helper.items.StickyHeaderDecoration;
import com.hikapro.backpack.view.View;
/**
* Created by tariel on 20/04/16.
@ -57,9 +61,10 @@ public class ItemListPresenter implements Presenter.ItemList {
model = null;
}
}
@Override
public android.view.View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// TODO check nn
if (savedInstanceState != null)
set = (Set) savedInstanceState.getSerializable(BUNDLE_SET_LIST_KEY);
else
@ -72,19 +77,16 @@ public class ItemListPresenter implements Presenter.ItemList {
final StickyHeaderDecoration decoration = new StickyHeaderDecoration(adapter);
recycler.addItemDecoration(decoration);
recycler.addItemDecoration(new DividerDecoration(getActivityContext()));
//recycler.addItemDecoration(new DividerDecoration(getActivityContext()));
recycler.addItemDecoration(new DividerDecoration2(getActivityContext(), R.drawable.divider, Util.dp2px(getAppContext(), 16)));
adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
@Override
public void onChanged() {
decoration.invalidateHeaders();
}
});
ItemSwipeCallback itemSwipeCallback = new ItemSwipeCallback(0, ItemTouchHelper.LEFT, adapter, getActivityContext());
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(itemSwipeCallback);
itemTouchHelper.attachToRecyclerView(recycler);
adapter.setUndoOn(true);
recycler.setHasFixedSize(true);
model.executeQuery();
footer = (LinearLayout) view.findViewById(R.id.item_list_footer);
packedCount = (TextView) footer.findViewById(R.id.footer_packed_count);
@ -97,21 +99,18 @@ public class ItemListPresenter implements Presenter.ItemList {
});
Activity activity = (Activity) getActivityContext();
if (activity != null) {
activity.invalidateOptionsMenu();
ActionBar actionBar = activity.getActionBar();
if (actionBar != null) {
actionBar.show();
actionBar.setTitle(set.getName());
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setDisplayShowCustomEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
/*
if ( model.getPackedQty() > 0) {
footer.setVisibility(android.view.View.VISIBLE);
String str = String.format("%s %d / %d",
getActivityContext().getResources().getString(R.string.packed), model.getPackedQty(),
model.getActiveItemsCount());
packedCount.setText(str);
}
*/
return view;
}
@Override
@ -146,7 +145,7 @@ public class ItemListPresenter implements Presenter.ItemList {
@Override
public void setVisibility() {
if (model.getPackedQty() == model.getActiveItemsCount()) {
if (model.getPackedQty() > 0 && model.getPackedQty() == model.getActiveItemsCount()) {
footer.setVisibility(android.view.View.VISIBLE);
} else if ( model.getPackedQty() > 0) {
footer.setVisibility(android.view.View.VISIBLE);
@ -156,19 +155,13 @@ public class ItemListPresenter implements Presenter.ItemList {
}
private void showPackedItems () {
getView().showPackedItems(set);
}
@Override
public void showDetails(int itemId) {
Item item = model.findItem(itemId);
if (item != null)
getView().showItemDetail(item);
else
showMessage(String.format("Item with Id %d is not found.", itemId));
public void showDetails(int position) {
getView().showItemDetail(getCurrentSet().getId(), model, position);
}
// process <--
@ -179,6 +172,7 @@ public class ItemListPresenter implements Presenter.ItemList {
this.view = new WeakReference<>(view);
this.set = getView().getSet();
}
@Override
public void setModel(Model.Item model) {
this.model = model;
@ -197,6 +191,7 @@ public class ItemListPresenter implements Presenter.ItemList {
return null;
}
}
@Override
public Context getActivityContext() {
try {
@ -229,4 +224,45 @@ public class ItemListPresenter implements Presenter.ItemList {
public Set getCurrentSet() {
return set;
}
@Override
public void unpack(int setId) {
model.unpackSet(setId);
}
@Override
public void restore(final int setId) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivityContext(), AlertDialog.THEME_HOLO_DARK);
builder.setMessage(R.string.dlg_restore_txt)
.setTitle(R.string.dlg_restore_header);
builder.setPositiveButton(R.string.ok_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
model.restoreSet(setId);
}
});
builder.setNegativeButton(R.string.cancel_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog dialog = builder.create();
dialog.show();
//Button button = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
//button.setBackgroundColor(Color.GREEN);
/*
Drawable d = button.getBackground();
PorterDuffColorFilter filter = new PorterDuffColorFilter(Color.GREEN, PorterDuff.Mode.SRC_ATOP);
d.setColorFilter(filter);*/
//button = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
//button.setBackgroundColor(Color.GRAY);
/*
d = button.getBackground();
filter = new PorterDuffColorFilter(Color.GRAY, PorterDuff.Mode.SRC_ATOP);
d.setColorFilter(filter);*/
}
}

View File

@ -1,5 +1,7 @@
package hikapro.com.backpack.presenter;
package com.hikapro.backpack.presenter;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
@ -9,15 +11,16 @@ import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import hikapro.com.backpack.R;
import hikapro.com.backpack.model.entities.Set;
import hikapro.com.backpack.presenter.adapters.PackedListAdapter;
import hikapro.com.backpack.presenter.adapters.helper.items.DividerDecoration;
import hikapro.com.backpack.presenter.adapters.helper.items.ItemSwipeCallback;
import hikapro.com.backpack.presenter.adapters.helper.items.StickyHeaderDecoration;
import com.hikapro.backpack.R;
import com.hikapro.backpack.model.entities.Set;
import com.hikapro.backpack.presenter.adapters.PackedListAdapter;
import com.hikapro.backpack.presenter.adapters.helper.Util;
import com.hikapro.backpack.presenter.adapters.helper.items.DividerDecoration;
import com.hikapro.backpack.presenter.adapters.helper.items.DividerDecoration2;
import com.hikapro.backpack.presenter.adapters.helper.items.ItemSwipeCallback;
import com.hikapro.backpack.presenter.adapters.helper.items.StickyHeaderDecoration;
/**
* Created by tariel on 13/05/16.
@ -48,18 +51,15 @@ public class PackedListPresenter extends ItemListPresenter {
final StickyHeaderDecoration decoration = new StickyHeaderDecoration(adapter);
recycler.addItemDecoration(decoration);
recycler.addItemDecoration(new DividerDecoration(getActivityContext()));
//recycler.addItemDecoration(new DividerDecoration(getActivityContext()));
recycler.addItemDecoration(new DividerDecoration2(getActivityContext(), R.drawable.divider, Util.dp2px(getAppContext(), 16)));
adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
@Override
public void onChanged() {
decoration.invalidateHeaders();
}
});
ItemSwipeCallback itemSwipeCallback = new ItemSwipeCallback(0, ItemTouchHelper.LEFT, adapter, getActivityContext());
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(itemSwipeCallback);
itemTouchHelper.attachToRecyclerView(recycler);
adapter.setUndoOn(true);
recycler.setHasFixedSize(true);
model.executeQuery();
@ -67,17 +67,7 @@ public class PackedListPresenter extends ItemListPresenter {
packedCount = (TextView) view.findViewById(R.id.header_packed_count);
unpackButton = (Button) view.findViewById(R.id.unpack_button);
if (model.getPackedQty() == model.getActiveItemsCount()) {
backToList.setVisibility(View.INVISIBLE);
packedCount.setVisibility(View.INVISIBLE);
unpackButton.setVisibility(View.VISIBLE);
} else {
backToList.setVisibility(View.VISIBLE);
packedCount.setVisibility(View.VISIBLE);
unpackButton.setVisibility(View.INVISIBLE);
}
setVisibility();
unpackButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
@ -94,12 +84,20 @@ public class PackedListPresenter extends ItemListPresenter {
}
});
/*
String str = String.format("%s %d / %d",
getActivityContext().getResources().getString(R.string.packed),
model.getPackedQty(), model.getActiveItemsCount());
packedCount.setText(str);
*/
Activity activity = (Activity) getActivityContext();
if (activity != null) {
activity.invalidateOptionsMenu();
ActionBar actionBar = activity.getActionBar();
if (actionBar != null) {
actionBar.show();
actionBar.setTitle(set.getName());
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setDisplayShowCustomEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
return view;
}

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.presenter;
package com.hikapro.backpack.presenter;
import android.content.Context;
import android.graphics.Bitmap;
@ -7,12 +7,10 @@ import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import hikapro.com.backpack.model.Model;
import hikapro.com.backpack.model.entities.Item;
import hikapro.com.backpack.model.entities.Set;
import hikapro.com.backpack.view.recycler.DetailViewHolder;
import hikapro.com.backpack.view.recycler.ItemViewHolder;
import hikapro.com.backpack.view.recycler.SetViewHolder;
import com.hikapro.backpack.model.Model;
import com.hikapro.backpack.model.entities.Item;
import com.hikapro.backpack.model.entities.Set;
import com.hikapro.backpack.view.View;
/**
* Created by tariel on 19/04/16.
@ -32,11 +30,12 @@ public interface Presenter {
void showItemList(Set set);
void onDestroy(boolean isChangingConfiguration);
android.view.View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);
void setView(hikapro.com.backpack.view.View.SetList view);
void setView(com.hikapro.backpack.view.View.SetList view);
void setModel(Model.Set model);
Model.Set getModel();
void notifyDataSetChanged();
void showMessage(String message);
void startProgress();
void stopProgress();
//GLM_add_resources_SetList
void onItemDismiss(int position);
@ -48,7 +47,7 @@ public interface Presenter {
void onDestroy(boolean isChangingConfiguration);
android.view.View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);
void setView(hikapro.com.backpack.view.View.ItemList view);
void setView(com.hikapro.backpack.view.View.ItemList view);
void setModel(Model.Item model);
Model.Item getModel();
void notifyDataSetChanged();
@ -57,21 +56,42 @@ public interface Presenter {
Set getCurrentSet();
void showMessage(String message);
void onSaveInstanceState(Bundle outState);
void showDetails(int itemId);
void showDetails(int position);
void filter(String query);
void unpack(int setId);
void restore(int setId);
}
interface ItemDetail extends Base {
void setView(hikapro.com.backpack.view.View.ItemDetail view);
void setView(com.hikapro.backpack.view.View.ItemDetail view);
void setModel(Model.Detail model);
Model.Detail getModel();
void notifyDataSetChanged();
void showMessage(String message);
void notifyPictureChanged();
void onDestroy(boolean isChangingConfiguration);
android.view.View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);
void onSaveInstanceState(Bundle outState);
Item getCurrentItem();
void displayPicture(Bitmap bitmap);
int getSetId();
}
interface Share extends Base {
void setView(View.Share view);
void setModel(Model.Share model);
Model.Share getModel();
void onDestroy(boolean isChangingConfiguration);
android.view.View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);
}
interface Add extends Base {
void setView(View.Add view);
void setModel(Model.Add model);
Model.Add getModel();
void onDestroy(boolean isChangingConfiguration);
android.view.View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);
void notifyDataSetChanged(boolean found);
void onAddItemClick(Item item);
}

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.presenter;
package com.hikapro.backpack.presenter;
import android.app.Activity;
import android.content.Context;
@ -9,19 +9,20 @@ import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.lang.ref.WeakReference;
import java.util.Collections;
import hikapro.com.backpack.R;
import hikapro.com.backpack.model.Model;
import hikapro.com.backpack.model.entities.Set;
import hikapro.com.backpack.presenter.adapters.SetListAdapter;
import hikapro.com.backpack.presenter.adapters.helper.sets.OnStartDragListener;
import hikapro.com.backpack.presenter.adapters.helper.sets.SimpleItemTouchHelperCallback;
import hikapro.com.backpack.view.View;
import hikapro.com.backpack.view.recycler.SetViewHolder;
import com.hikapro.backpack.R;
import com.hikapro.backpack.model.Model;
import com.hikapro.backpack.model.entities.Set;
import com.hikapro.backpack.presenter.adapters.SetListAdapter;
import com.hikapro.backpack.presenter.adapters.helper.sets.OnStartDragListener;
import com.hikapro.backpack.presenter.adapters.helper.sets.SimpleItemTouchHelperCallback;
import com.hikapro.backpack.view.View;
import com.hikapro.backpack.view.recycler.SetViewHolder;
/**
* Created by tariel on 20/04/16.
@ -31,6 +32,9 @@ public class SetListPresenter implements Presenter.SetList {
private WeakReference<View.SetList> view;
private Model.Set model;
private SetListAdapter adapter;
private ViewGroup progressBarContainer;
private ProgressBar progressBar;
private RecyclerView setRecycler;
//GLM_add_resources_SetList
@ -72,8 +76,12 @@ public class SetListPresenter implements Presenter.SetList {
public android.view.View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
android.view.View view = inflater.inflate(R.layout.fragment_set_list, container, false);
progressBarContainer = (ViewGroup) view.findViewById(R.id.set_progress_container);
progressBar = (ProgressBar) progressBarContainer.findViewById(R.id.set_progress);
LinearLayoutManager llm = new LinearLayoutManager(getActivityContext());
RecyclerView setRecycler = (RecyclerView) view.findViewById(R.id.set_recycler);
setRecycler = (RecyclerView) view.findViewById(R.id.set_recycler);
setRecycler.setLayoutManager(llm);
setRecycler.setAdapter(adapter);
setRecycler.setItemAnimator(new DefaultItemAnimator());
@ -134,11 +142,6 @@ public class SetListPresenter implements Presenter.SetList {
return model;
}
@Override
public void showMessage(String message) {
Toast.makeText(getView().getAppContext(), message, Toast.LENGTH_SHORT).show();
}
// other impl <--
private View.SetList getView() throws NullPointerException {
@ -148,6 +151,18 @@ public class SetListPresenter implements Presenter.SetList {
throw new NullPointerException("View is unavailable");
}
@Override
public void startProgress() {
setRecycler.setVisibility(android.view.View.GONE);
progressBarContainer.setVisibility(android.view.View.VISIBLE);
}
@Override
public void stopProgress() {
setRecycler.setVisibility(android.view.View.VISIBLE);
progressBarContainer.setVisibility(android.view.View.GONE);
}
//GLM_add_resources_SetList
@Override
public void onStartDrag(RecyclerView.ViewHolder viewHolder) {
@ -158,7 +173,7 @@ public class SetListPresenter implements Presenter.SetList {
if (getView() != null)
getView().showItemList(set);
else
showMessage("There is no view in presenter");
Toast.makeText(getActivityContext(), "There is no view in presenter", Toast.LENGTH_SHORT).show();
}
public void onLongClick(SetViewHolder holder) {

View File

@ -0,0 +1,142 @@
package com.hikapro.backpack.presenter;
import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.share.Sharer;
import com.facebook.share.model.ShareHashtag;
import com.facebook.share.model.ShareLinkContent;
import com.facebook.share.widget.ShareDialog;
import com.hikapro.backpack.R;
import com.hikapro.backpack.model.Model;
import com.hikapro.backpack.view.View;
import java.lang.ref.WeakReference;
/**
* Created by tariel on 16/05/16.
*/
public class SharePresenter implements Presenter.Share {
private ShareDialog shareDialog;
private CallbackManager callbackManager;
private Button facebookButton;
private Button twitterButton;
private WeakReference<View.Share> view;
private Model.Share model;
@Override
public Context getAppContext() {
try {
return getView().getAppContext();
} catch (NullPointerException e) {
return null;
}
}
@Override
public Context getActivityContext() {
try {
return getView().getActivityContext();
} catch (NullPointerException e) {
return null;
}
}
@Override
public void setView(View.Share view) {
this.view = new WeakReference<>(view);
}
@Override
public void setModel(Model.Share model) {
this.model = model;
}
@Override
public Model.Share getModel() {
return model;
}
@Override
public void onDestroy(boolean isChangingConfiguration) {
view = null;
model.onDestroy(isChangingConfiguration);
if ( !isChangingConfiguration ) {
model = null;
}
}
@Override
public android.view.View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
android.view.View v = inflater.inflate(R.layout.fragment_share, container, false);
FacebookSdk.sdkInitialize(getAppContext());
//AppEventsLogger.activateApp(getActivityContext());
callbackManager = CallbackManager.Factory.create();
shareDialog = new ShareDialog((Activity) getActivityContext());
facebookButton = (Button) v.findViewById(R.id.facebook_share_button);
twitterButton = (Button) v.findViewById(R.id.twitter_share_button);
shareDialog.registerCallback(callbackManager, new
FacebookCallback<Sharer.Result>() {
@Override
public void onSuccess(Sharer.Result result) {}
@Override
public void onCancel() {}
@Override
public void onError(FacebookException error) {}
});
facebookButton.setOnClickListener(new android.view.View.OnClickListener() {
@Override
public void onClick(android.view.View v) {
if (ShareDialog.canShow(ShareLinkContent.class)) {
ShareLinkContent linkContent = new ShareLinkContent.Builder()
.setContentTitle("Test Pack With Me app")
.setContentDescription("Test of facebook integration")
.setContentUrl(Uri.parse("http://developers.facebook.com/android"))
.setShareHashtag(new ShareHashtag.Builder()
.setHashtag("#PackWithMe")
.build())
.build();
shareDialog.show(linkContent);
}
}
});
twitterButton.setOnClickListener(new android.view.View.OnClickListener() {
@Override
public void onClick(android.view.View v) {
Toast.makeText(getActivityContext(), "Not implemented!", Toast.LENGTH_SHORT).show();
}
});
return v;
}
private View.Share getView() throws NullPointerException {
if ( view != null )
return view.get();
else
throw new NullPointerException("View is unavailable");
}
}

View File

@ -0,0 +1,53 @@
package com.hikapro.backpack.presenter.adapters;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import com.hikapro.backpack.R;
import com.hikapro.backpack.model.entities.Item;
import com.hikapro.backpack.presenter.Presenter;
import com.hikapro.backpack.view.recycler.AddItemViewHolder;
import com.hikapro.backpack.view.recycler.ItemViewHolder;
/**
* Created by tariel on 18/05/16.
*/
public class AddListAdapter extends RecyclerView.Adapter<AddItemViewHolder> {
private Presenter.Add presenter;
public AddListAdapter(Presenter.Add presenter) {
this.presenter = presenter;
}
@Override
public int getItemCount() {
return presenter.getModel().getItemsCount();
}
@Override
public void onBindViewHolder(AddItemViewHolder holder, int position) {
final Item item = presenter.getModel().getItemByPosition(position);
holder.name.setText(item.getName());
holder.category.setText(presenter.getModel().getCategoryById(item.getCategory()).getName());
holder.alreadyInList.setVisibility(item.InList ? View.VISIBLE : View.GONE);
holder.item.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
presenter.onAddItemClick(item);
}
});
}
@Override
public AddItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
AddItemViewHolder viewHolder;
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_add,
parent, false);
viewHolder = new AddItemViewHolder(v);
return viewHolder;
}
}

View File

@ -0,0 +1,179 @@
package com.hikapro.backpack.presenter.adapters;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import com.hikapro.backpack.R;
import com.hikapro.backpack.model.entities.Item;
import com.hikapro.backpack.presenter.Presenter;
import com.hikapro.backpack.presenter.adapters.helper.Util;
import com.hikapro.backpack.presenter.adapters.helper.items.swipe2.SwipableElement;
import com.hikapro.backpack.presenter.adapters.helper.items.swipe2.SwipeMenu;
import com.hikapro.backpack.presenter.adapters.helper.items.swipe2.SwipeMenuItem;
import com.hikapro.backpack.presenter.adapters.helper.items.swipe2.SwipeMenuLayout;
import com.hikapro.backpack.view.recycler.ItemViewHolder;
/**
* Created by tariel on 23/04/16.
*/
public class ItemDetailAdapter extends RecyclerView.Adapter<ItemViewHolder> {
private Presenter.ItemDetail presenter;
public ItemDetailAdapter(Presenter.ItemDetail presenter) {
this.presenter = presenter;
}
@Override
public int getItemCount() {
return presenter.getModel().getCount();
}
@Override
public void onBindViewHolder(final ItemViewHolder holder, final int position) {
final Item item = presenter.getModel().getCurrentItem();
holder.cb_item.setChecked(item.isPacked());
holder.tv_text.setText(item.getName() + " " + item.getId() + " pos " + position);
holder.im_info.setVisibility(View.GONE);
if (item.isPendingRemoval()) {
holder.tv_text.setPaintFlags(holder.tv_text.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
holder.cb_item.setVisibility(View.GONE);
} else {
holder.cb_item.setVisibility(View.VISIBLE);
holder.tv_text.setPaintFlags(holder.tv_text.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
}
holder.cb_item.setOnClickListener(new android.view.View.OnClickListener() {
@Override
public void onClick(View v) {
if (holder.cb_item.isChecked()) {
pack(item);
} else {
unpack(item);
}
}
});
final SwipeMenuLayout menuLayout = (SwipeMenuLayout)holder.menu;
SwipeMenu menu = new SwipeMenu(presenter.getActivityContext());
menuLayout.removeAllViews();
// create menu items here
if (!item.isPendingRemoval()) {
// create "leave at home" item
SwipeMenuItem leaveAtHomeItem = new SwipeMenuItem(menu.getContext());
// set id
leaveAtHomeItem.setId(ItemListAdapter.ID_LEAVE_AT_HOME);
// set item background
leaveAtHomeItem.setBackground(R.color.colorLeaveAtHomeBtnBackground);
// set item width
leaveAtHomeItem.setWidth(Util.dp2px(presenter.getActivityContext(), 120));
// set item title
leaveAtHomeItem.setTitle(R.string.leave_at_home_button);
// set item title font size
leaveAtHomeItem.setTitleSize(14);
// set item title font color
leaveAtHomeItem.setTitleColor(Color.WHITE);
// add to menu
menu.addMenuItem(leaveAtHomeItem);
} else {
// create "add to bag" item
SwipeMenuItem addToBagItem = new SwipeMenuItem(menu.getContext());
// set id
addToBagItem.setId(ItemListAdapter.ID_ADD_TO_BAG);
// set item background
addToBagItem.setBackground(R.color.colorAddToBagBtnBackground);
// set item width
addToBagItem.setWidth(Util.dp2px(presenter.getActivityContext(), 120));
// set item title
addToBagItem.setTitle(R.string.add_to_bag_button);
// set item title font size
addToBagItem.setTitleSize(14);
// set item title font color
addToBagItem.setTitleColor(Color.WHITE);
// add to menu
menu.addMenuItem(addToBagItem);
// create "return to list" item
SwipeMenuItem returnToListItem = new SwipeMenuItem(menu.getContext());
// set id
returnToListItem.setId(ItemListAdapter.ID_RETURN_TO_LIST);
// set item background
returnToListItem.setBackground(R.color.colorReturnToListBtnBackground);
// set item width
returnToListItem.setWidth(Util.dp2px(presenter.getActivityContext(), 120));
// set item title
returnToListItem.setTitle(R.string.return_to_list_button);
// set item title font size
returnToListItem.setTitleSize(14);
// set item title font color
returnToListItem.setTitleColor(Color.WHITE);
// add to menu
menu.addMenuItem(returnToListItem);
}
View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case ItemListAdapter.ID_DELETE:
// no delete
break;
case ItemListAdapter.ID_LEAVE_AT_HOME:
leave(item);
break;
case ItemListAdapter.ID_RETURN_TO_LIST:
leaveCancel(item);
break;
case ItemListAdapter.ID_ADD_TO_BAG:
pack(item);
break;
}
menuLayout.notifyOnMenuItemClick();
}
};
menuLayout.addMenu(menu, onClickListener);
}
@Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
ItemViewHolder viewHolder;
View content = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_element, parent, false);
SwipeMenuLayout menu = new SwipeMenuLayout(parent.getContext());
menu.setId(R.id.menu);
SwipableElement container = new SwipableElement(parent.getContext(), content, menu);
container.setSwipeDirection(SwipableElement.DIRECTION_LEFT);
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, Util.dp2px(parent.getContext(),66));
container.setOrientation(LinearLayout.HORIZONTAL);
container.setLayoutParams(params);
viewHolder = new ItemViewHolder(container);
return viewHolder;
}
public void leave(Item item) {
presenter.getModel().pendingRemove(item);
}
public void pack(Item item) {
presenter.getModel().packItem(item);
}
public void unpack(Item item) {
presenter.getModel().unpackItem(item);
}
public void leaveCancel(Item item) {
presenter.getModel().pendingRemoveCancel(item);
}
}

View File

@ -0,0 +1,262 @@
package com.hikapro.backpack.presenter.adapters;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.hikapro.backpack.App;
import com.hikapro.backpack.R;
import com.hikapro.backpack.model.entities.Category;
import com.hikapro.backpack.model.entities.Item;
import com.hikapro.backpack.presenter.Presenter;
import com.hikapro.backpack.presenter.adapters.helper.Util;
import com.hikapro.backpack.presenter.adapters.helper.items.StickyHeaderAdapter;
import com.hikapro.backpack.presenter.adapters.helper.items.swipe2.SwipableElement;
import com.hikapro.backpack.presenter.adapters.helper.items.swipe2.SwipeMenu;
import com.hikapro.backpack.presenter.adapters.helper.items.swipe2.SwipeMenuItem;
import com.hikapro.backpack.presenter.adapters.helper.items.swipe2.SwipeMenuLayout;
import com.hikapro.backpack.view.recycler.HeaderViewHolder;
import com.hikapro.backpack.view.recycler.ItemViewHolder;
/**
* Created by tariel on 01/05/16.
*/
public class ItemListAdapter extends RecyclerView.Adapter<ItemViewHolder> implements StickyHeaderAdapter<HeaderViewHolder> {
protected static final int ID_DELETE = 1;
protected static final int ID_LEAVE_AT_HOME = 2;
protected static final int ID_ADD_TO_BAG = 3;
protected static final int ID_RETURN_TO_LIST = 4;
protected Presenter.ItemList presenter;
protected boolean checkAll;
public ItemListAdapter(Presenter.ItemList presenter) {
this.presenter = presenter;
}
@Override
public int getItemCount() {
int res = presenter.getModel().getItemsCount();
return res;
}
@Override
public long getItemId(int position) {
long ret = presenter.getModel().getItemId(position);
return ret;
}
@Override
public void onBindViewHolder(final ItemViewHolder holder, final int position) {
final Item item = presenter.getModel().getItemByPosition(position);
holder.cb_item.setChecked(checkAll);
holder.tv_text.setText(item.getName() + " " + item.getId() + " pos " + position);
//holder.tv_text.setTypeface(mainFace);
if (item.isPendingRemoval()) {
holder.tv_text.setPaintFlags(holder.tv_text.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
holder.cb_item.setVisibility(View.GONE);
} else {
holder.cb_item.setVisibility(View.VISIBLE);
holder.tv_text.setPaintFlags(holder.tv_text.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
}
holder.cb_item.setOnClickListener(new android.view.View.OnClickListener() {
@Override
public void onClick(View v) {
if (holder.cb_item.isChecked()) {
pack(item);
} else {
unpack(item);
}
}
});
holder.im_info.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
presenter.showDetails(position);
}
});
final SwipeMenuLayout menuLayout = (SwipeMenuLayout)holder.menu;
final SwipeMenu menu = new SwipeMenu(presenter.getActivityContext());
menuLayout.removeAllViews();
// create menu items here
if (!item.isPendingRemoval()) {
// create "leave at home" item
SwipeMenuItem leaveAtHomeItem = new SwipeMenuItem(menu.getContext());
// set id
leaveAtHomeItem.setId(ID_LEAVE_AT_HOME);
// set item background
leaveAtHomeItem.setBackground(R.color.colorLeaveAtHomeBtnBackground);
// set item width
leaveAtHomeItem.setWidth(Util.dp2px(presenter.getActivityContext(), 120));
// set item title
leaveAtHomeItem.setTitle(R.string.leave_at_home_button);
// set item title font size
leaveAtHomeItem.setTitleSize(14);
// set item title font color
leaveAtHomeItem.setTitleColor(Color.WHITE);
// add to menu
menu.addMenuItem(leaveAtHomeItem);
} else {
// create "add to bag" item
SwipeMenuItem addToBagItem = new SwipeMenuItem(menu.getContext());
// set id
addToBagItem.setId(ID_ADD_TO_BAG);
// set item background
addToBagItem.setBackground(R.color.colorAddToBagBtnBackground);
// set item width
addToBagItem.setWidth(Util.dp2px(presenter.getActivityContext(), 120));
// set item title
addToBagItem.setTitle(R.string.add_to_bag_button);
// set item title font size
addToBagItem.setTitleSize(14);
// set item title font color
addToBagItem.setTitleColor(Color.WHITE);
// add to menu
menu.addMenuItem(addToBagItem);
// create "return to list" item
SwipeMenuItem returnToListItem = new SwipeMenuItem(menu.getContext());
// set id
returnToListItem.setId(ID_RETURN_TO_LIST);
// set item background
returnToListItem.setBackground(R.color.colorReturnToListBtnBackground);
// set item width
returnToListItem.setWidth(Util.dp2px(presenter.getActivityContext(), 120));
// set item title
returnToListItem.setTitle(R.string.return_to_list_button);
// set item title font size
returnToListItem.setTitleSize(14);
// set item title font color
returnToListItem.setTitleColor(Color.WHITE);
// add to menu
menu.addMenuItem(returnToListItem);
}
// create "delete" item
SwipeMenuItem deleteItem = new SwipeMenuItem(menu.getContext());
// set id
deleteItem.setId(ID_DELETE);
// set item background
deleteItem.setBackground(R.color.colorDeleteBtnBackground);
// set item width
deleteItem.setWidth(Util.dp2px(presenter.getActivityContext(),120));
// set item title
deleteItem.setTitle(R.string.delete_button);
// set item title font size
deleteItem.setTitleSize(14);
// set item title font color
deleteItem.setTitleColor(Color.WHITE);
// add to menu
menu.addMenuItem(deleteItem);
View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case ID_DELETE:
remove(item);
break;
case ID_LEAVE_AT_HOME:
leave(item);
break;
case ID_RETURN_TO_LIST:
leaveCancel(item);
break;
case ID_ADD_TO_BAG:
pack(item);
break;
}
menuLayout.notifyOnMenuItemClick();
}
};
menuLayout.addMenu(menu, onClickListener);
}
@Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
ItemViewHolder viewHolder;
View content = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_element, parent, false);
SwipeMenuLayout menu = new SwipeMenuLayout(parent.getContext());
menu.setId(R.id.menu);
SwipableElement container = new SwipableElement(parent.getContext(), content, menu);
container.setSwipeDirection(SwipableElement.DIRECTION_LEFT);
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, Util.dp2px(parent.getContext(),66));
container.setOrientation(LinearLayout.HORIZONTAL);
container.setLayoutParams(params);
viewHolder = new ItemViewHolder(container);
return viewHolder;
}
public void filter(String query) {
presenter.getModel().filter(query);
notifyDataSetChanged();
}
@Override
public long getHeaderId(int position) {
/*if (position == 0) {
return -1;
} else {*/
return presenter.getModel().getHeaderId(position);
//}
}
@Override
public HeaderViewHolder onCreateHeaderViewHolder(ViewGroup parent) {
HeaderViewHolder viewHolder;
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.header_element, parent, false);
viewHolder = new HeaderViewHolder(v);
return viewHolder;
}
@Override
public void onBindHeaderViewHolder(HeaderViewHolder holder, int position) {
Category category = presenter.getModel().getCategoryByPosition(position);
holder.id = category.getId();
holder.title.setText(category.getName());
holder.title.setTypeface(App.getMainFace());
holder.title.setBackgroundColor(0x2B1E15);
}
public void leave(Item item) {
presenter.getModel().pendingRemove(item);
}
public void leaveCancel(Item item) {
presenter.getModel().pendingRemoveCancel(item);
}
public void remove(Item item) {
presenter.getModel().remove(item);
}
public void pack(Item item) {
if (!item.isPacked())
presenter.getModel().packItem(item);
}
public void unpack(Item item) {
if (item.isPacked())
presenter.getModel().unpackItem(item);
}
public void setCheckAll(boolean checkAll) {
this.checkAll = checkAll;
}
}

View File

@ -0,0 +1,172 @@
package com.hikapro.backpack.presenter.adapters;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
import android.widget.Toast;
import com.hikapro.backpack.R;
import com.hikapro.backpack.model.entities.Item;
import com.hikapro.backpack.presenter.Presenter;
import com.hikapro.backpack.presenter.adapters.helper.Util;
import com.hikapro.backpack.presenter.adapters.helper.items.swipe2.SwipeMenu;
import com.hikapro.backpack.presenter.adapters.helper.items.swipe2.SwipeMenuItem;
import com.hikapro.backpack.presenter.adapters.helper.items.swipe2.SwipeMenuLayout;
import com.hikapro.backpack.view.recycler.ItemViewHolder;
/**
* Created by tariel on 12/05/16.
*/
public class PackedListAdapter extends ItemListAdapter {
public PackedListAdapter(Presenter.ItemList presenter) {
super(presenter);
}
@Override
public void onBindViewHolder(final ItemViewHolder holder, final int position) {
final Item item = presenter.getModel().getItemByPosition(position);
holder.cb_item.setChecked(checkAll);
holder.tv_text.setText(item.getName() + " " + item.getId() + " pos " + position);
if (item.isPendingRemoval()) {
holder.tv_text.setPaintFlags(holder.tv_text.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
holder.cb_item.setVisibility(View.GONE);
} else {
holder.cb_item.setVisibility(View.VISIBLE);
holder.tv_text.setPaintFlags(holder.tv_text.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
}
holder.cb_item.setOnClickListener(new android.view.View.OnClickListener() {
@Override
public void onClick(View v) {
if (holder.cb_item.isChecked()) {
pack(item);
} else {
unpack(item);
}
}
});
holder.im_info.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
presenter.showDetails(position);
}
});
final SwipeMenuLayout menuLayout = (SwipeMenuLayout)holder.menu;
SwipeMenu menu = new SwipeMenu(presenter.getActivityContext());
menuLayout.removeAllViews();
// create menu items here
if (!item.isPendingRemoval()) {
// create "leave at home" item
SwipeMenuItem leaveAtHomeItem = new SwipeMenuItem(menu.getContext());
// set id
leaveAtHomeItem.setId(ID_LEAVE_AT_HOME);
// set item background
leaveAtHomeItem.setBackground(R.color.colorLeaveAtHomeBtnBackground);
// set item width
leaveAtHomeItem.setWidth(Util.dp2px(presenter.getActivityContext(), 120));
// set item title
leaveAtHomeItem.setTitle(R.string.leave_at_home_button);
// set item title font size
leaveAtHomeItem.setTitleSize(14);
// set item title font color
leaveAtHomeItem.setTitleColor(Color.WHITE);
// add to menu
menu.addMenuItem(leaveAtHomeItem);
} else {
// create "add to bag" item
SwipeMenuItem addToBagItem = new SwipeMenuItem(menu.getContext());
// set id
addToBagItem.setId(ID_ADD_TO_BAG);
// set item background
addToBagItem.setBackground(R.color.colorAddToBagBtnBackground);
// set item width
addToBagItem.setWidth(Util.dp2px(presenter.getActivityContext(), 120));
// set item title
addToBagItem.setTitle(R.string.add_to_bag_button);
// set item title font size
addToBagItem.setTitleSize(14);
// set item title font color
addToBagItem.setTitleColor(Color.WHITE);
// add to menu
menu.addMenuItem(addToBagItem);
// create "return to list" item
SwipeMenuItem returnToListItem = new SwipeMenuItem(menu.getContext());
// set id
returnToListItem.setId(ID_RETURN_TO_LIST);
// set item background
returnToListItem.setBackground(R.color.colorReturnToListBtnBackground);
// set item width
returnToListItem.setWidth(Util.dp2px(presenter.getActivityContext(), 120));
// set item title
returnToListItem.setTitle(R.string.return_to_list_button);
// set item title font size
returnToListItem.setTitleSize(14);
// set item title font color
returnToListItem.setTitleColor(Color.WHITE);
// add to menu
menu.addMenuItem(returnToListItem);
}
// create "delete" item
SwipeMenuItem deleteItem = new SwipeMenuItem(menu.getContext());
// set id
deleteItem.setId(ID_DELETE);
// set item background
deleteItem.setBackground(R.color.colorDeleteBtnBackground);
// set item width
deleteItem.setWidth(Util.dp2px(presenter.getActivityContext(),120));
// set item title
deleteItem.setTitle(R.string.delete_button);
// set item title font size
deleteItem.setTitleSize(14);
// set item title font color
deleteItem.setTitleColor(Color.WHITE);
// add to menu
menu.addMenuItem(deleteItem);
View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case ID_DELETE:
remove(item);
break;
case ID_LEAVE_AT_HOME:
leave(item);
break;
case ID_RETURN_TO_LIST:
unpack(item);
break;
case ID_ADD_TO_BAG:
pack(item);
break;
}
menuLayout.notifyOnMenuItemClick();
}
};
menuLayout.addMenu(menu, onClickListener);
}
@Override
public void remove(Item item) {
if (item.isPendingRemoval()) {
presenter.getModel().unpackItem(item);
presenter.getModel().remove(item);
}
else
presenter.getModel().pendingRemove(item);
}
@Override
public void leave(Item item) {
presenter.getModel().pendingRemove(item);
}
}

View File

@ -1,14 +1,16 @@
package hikapro.com.backpack.presenter.adapters;
package com.hikapro.backpack.presenter.adapters;
import android.graphics.Typeface;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import hikapro.com.backpack.R;
import hikapro.com.backpack.presenter.SetListPresenter;
import hikapro.com.backpack.presenter.adapters.helper.sets.ItemTouchHelperAdapter;
import hikapro.com.backpack.view.recycler.SetViewHolder;
import com.hikapro.backpack.App;
import com.hikapro.backpack.R;
import com.hikapro.backpack.presenter.SetListPresenter;
import com.hikapro.backpack.presenter.adapters.helper.sets.ItemTouchHelperAdapter;
import com.hikapro.backpack.view.recycler.SetViewHolder;
/**
* Created by tariel on 20/04/16.
@ -25,7 +27,7 @@ public class SetListAdapter extends RecyclerView.Adapter<SetViewHolder> impleme
@Override
public void onBindViewHolder(final SetViewHolder holder, int position) {
final hikapro.com.backpack.model.entities.Set set = presenter.getModel().getSetByPosition(position);
final com.hikapro.backpack.model.entities.Set set = presenter.getModel().getSetByPosition(position);
if (rightBracket == null || rightBracket.isEmpty()) {
@ -37,6 +39,7 @@ public class SetListAdapter extends RecyclerView.Adapter<SetViewHolder> impleme
}
holder.textView.setText(set.getName() + " " + rightBracket);
holder.textView.setTypeface(App.getMainFace());
String info = String.format("%s %d / %d",
presenter.getActivityContext().getResources().getString(R.string.packed),
set.getPackedQty(),

View File

@ -0,0 +1,296 @@
package com.hikapro.backpack.presenter.adapters.helper;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.RectF;
import android.os.Build;
import android.text.Layout.Alignment;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.SparseIntArray;
import android.util.TypedValue;
import android.widget.TextView;
public class AutoResizeTextView extends TextView {
private interface SizeTester {
/**
*
* @param suggestedSize
* Size of text to be tested
* @param availableSpace
* available space in which text must fit
* @return an integer < 0 if after applying {@code suggestedSize} to
* text, it takes less space than {@code availableSpace}, > 0
* otherwise
*/
public int onTestSize(int suggestedSize, RectF availableSpace);
}
private RectF mTextRect = new RectF();
private RectF mAvailableSpaceRect;
private SparseIntArray mTextCachedSizes;
private TextPaint mPaint;
private float mMaxTextSize;
private float mSpacingMult = 1.0f;
private float mSpacingAdd = 0.0f;
private float mMinTextSize = 20;
private int mWidthLimit;
private static final int NO_LINE_LIMIT = -1;
private int mMaxLines;
private boolean mEnableSizeCache = true;
private boolean mInitiallized;
public AutoResizeTextView(Context context) {
super(context);
initialize();
}
public AutoResizeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}
public AutoResizeTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initialize();
}
private void initialize() {
mPaint = new TextPaint(getPaint());
mMaxTextSize = getTextSize();
mAvailableSpaceRect = new RectF();
mTextCachedSizes = new SparseIntArray();
if (mMaxLines == 0) {
// no value was assigned during construction
mMaxLines = NO_LINE_LIMIT;
}
mInitiallized = true;
}
@Override
public void setText(final CharSequence text, BufferType type) {
super.setText(text, type);
adjustTextSize(text.toString());
}
@Override
public void setTextSize(float size) {
mMaxTextSize = size;
mTextCachedSizes.clear();
adjustTextSize(getText().toString());
}
@Override
public void setMaxLines(int maxlines) {
super.setMaxLines(maxlines);
mMaxLines = maxlines;
reAdjust();
}
public int getMaxLines() {
return mMaxLines;
}
@Override
public void setSingleLine() {
super.setSingleLine();
mMaxLines = 1;
reAdjust();
}
@Override
public void setSingleLine(boolean singleLine) {
super.setSingleLine(singleLine);
if (singleLine) {
mMaxLines = 1;
} else {
mMaxLines = NO_LINE_LIMIT;
}
reAdjust();
}
@Override
public void setLines(int lines) {
super.setLines(lines);
mMaxLines = lines;
reAdjust();
}
@Override
public void setTextSize(int unit, float size) {
Context c = getContext();
Resources r;
if (c == null)
r = Resources.getSystem();
else
r = c.getResources();
mMaxTextSize = TypedValue.applyDimension(unit, size,
r.getDisplayMetrics());
mTextCachedSizes.clear();
adjustTextSize(getText().toString());
}
@Override
public void setLineSpacing(float add, float mult) {
super.setLineSpacing(add, mult);
mSpacingMult = mult;
mSpacingAdd = add;
}
/**
* Set the lower text size limit and invalidate the view
*
* @param minTextSize
*/
public void setMinTextSize(float minTextSize) {
mMinTextSize = minTextSize;
reAdjust();
}
private void reAdjust() {
adjustTextSize(getText().toString());
}
private void adjustTextSize(String string) {
if (!mInitiallized) {
return;
}
int startSize = (int) mMinTextSize;
int heightLimit = getMeasuredHeight() - getCompoundPaddingBottom()
- getCompoundPaddingTop();
mWidthLimit = getMeasuredWidth() - getCompoundPaddingLeft()
- getCompoundPaddingRight();
mAvailableSpaceRect.right = mWidthLimit;
mAvailableSpaceRect.bottom = heightLimit;
super.setTextSize(
TypedValue.COMPLEX_UNIT_PX,
efficientTextSizeSearch(startSize, (int) mMaxTextSize,
mSizeTester, mAvailableSpaceRect));
}
private final SizeTester mSizeTester = new SizeTester() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public int onTestSize(int suggestedSize, RectF availableSPace) {
mPaint.setTextSize(suggestedSize);
String text = getText().toString();
boolean singleline = getMaxLines() == 1;
if (singleline) {
mTextRect.bottom = mPaint.getFontSpacing();
mTextRect.right = mPaint.measureText(text);
} else {
StaticLayout layout = new StaticLayout(text, mPaint,
mWidthLimit, Alignment.ALIGN_NORMAL, mSpacingMult,
mSpacingAdd, true);
// return early if we have more lines
if (getMaxLines() != NO_LINE_LIMIT
&& layout.getLineCount() > getMaxLines()) {
return 1;
}
mTextRect.bottom = layout.getHeight();
int maxWidth = -1;
for (int i = 0; i < layout.getLineCount(); i++) {
if (maxWidth < layout.getLineWidth(i)) {
maxWidth = (int) layout.getLineWidth(i);
}
}
mTextRect.right = maxWidth;
}
mTextRect.offsetTo(0, 0);
if (availableSPace.contains(mTextRect)) {
// may be too small, don't worry we will find the best match
return -1;
} else {
// too big
return 1;
}
}
};
/**
* Enables or disables size caching, enabling it will improve performance
* where you are animating a value inside TextView. This stores the font
* size against getText().length() Be careful though while enabling it as 0
* takes more space than 1 on some fonts and so on.
*
* @param enable
* enable font size caching
*/
public void enableSizeCache(boolean enable) {
mEnableSizeCache = enable;
mTextCachedSizes.clear();
adjustTextSize(getText().toString());
}
private int efficientTextSizeSearch(int start, int end,
SizeTester sizeTester, RectF availableSpace) {
if (!mEnableSizeCache) {
return binarySearch(start, end, sizeTester, availableSpace);
}
String text = getText().toString();
int key = text == null ? 0 : text.length();
int size = mTextCachedSizes.get(key);
if (size != 0) {
return size;
}
size = binarySearch(start, end, sizeTester, availableSpace);
mTextCachedSizes.put(key, size);
return size;
}
private static int binarySearch(int start, int end, SizeTester sizeTester,
RectF availableSpace) {
int lastBest = start;
int lo = start;
int hi = end - 1;
int mid = 0;
while (lo <= hi) {
mid = (lo + hi) >>> 1;
int midValCmp = sizeTester.onTestSize(mid, availableSpace);
if (midValCmp < 0) {
lastBest = lo;
lo = mid + 1;
} else if (midValCmp > 0) {
hi = mid - 1;
lastBest = hi;
} else {
return mid;
}
}
// make sure to return last best
// this is what should always be returned
return lastBest;
}
@Override
protected void onTextChanged(final CharSequence text, final int start,
final int before, final int after) {
super.onTextChanged(text, start, before, after);
reAdjust();
}
@Override
protected void onSizeChanged(int width, int height, int oldwidth,
int oldheight) {
mTextCachedSizes.clear();
super.onSizeChanged(width, height, oldwidth, oldheight);
if (width != oldwidth || height != oldheight) {
reAdjust();
}
}
}

View File

@ -0,0 +1,110 @@
package com.hikapro.backpack.presenter.adapters.helper;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import com.hikapro.backpack.R;
/**
* Created by tariel on 22/05/16.
*/
public class FlowLayout extends ViewGroup {
private int PADDING_X;
private int PADDING_Y;
private int mHeight;
public FlowLayout(Context context) {
super(context);
setPaddings(0,0);
}
public void setPaddings(int V, int H){
PADDING_X = H;
PADDING_Y = V;
}
protected void setPaddings(Context ctx, AttributeSet attrs){
TypedArray a = ctx
.obtainStyledAttributes(attrs, R.styleable.FlowLayout);
String H = a.getString(R.styleable.FlowLayout_paddingX);
String V = a.getString(R.styleable.FlowLayout_paddingY);
if (H == null || V == null)
setPaddings(V == null ? 0 : Integer.parseInt(V), H == null ? 0 :Integer.parseInt(H));
else {
setPaddings(Integer.parseInt(V), Integer.parseInt(H));
a.recycle();
}
}
public FlowLayout(Context context, AttributeSet attrs) {
super(context, attrs);
setPaddings(context,attrs);
}
public FlowLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setPaddings(context,attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
assert (MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.UNSPECIFIED);
final int width = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight();
int height = MeasureSpec.getSize(heightMeasureSpec) - getPaddingTop() - getPaddingBottom();
final int count = getChildCount();
int xpos = getPaddingLeft();
int ypos = getPaddingTop();
int childHeightMeasureSpec;
if(MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST)
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST);
else
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
mHeight = 0;
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
child.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST), childHeightMeasureSpec);
final int childw = child.getMeasuredWidth();
mHeight = Math.max(mHeight, child.getMeasuredHeight() + PADDING_Y);
if (xpos + childw > width) {
xpos = getPaddingLeft();
ypos += mHeight;
}
xpos += childw + PADDING_X;
}
}
if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.UNSPECIFIED) {
height = ypos + mHeight;
} else if(MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) {
if(ypos + mHeight < height) {
height = ypos + mHeight;
}
}
height += 5; // Fudge to avoid clipping bottom of last row.
setMeasuredDimension(width, height);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int width = r - l;
int xpos = getPaddingLeft();
int ypos = getPaddingTop();
for(int i = 0; i < getChildCount(); i++) {
final View child = getChildAt(i);
if(child.getVisibility() != GONE) {
final int childw = child.getMeasuredWidth();
final int childh = child.getMeasuredHeight();
if(xpos + childw > width) {
xpos = getPaddingLeft();
ypos += mHeight;
}
child.layout(xpos, ypos, xpos + childw, ypos + childh);
xpos += childw + PADDING_X;
}
}
}
}

View File

@ -0,0 +1,53 @@
package com.hikapro.backpack.presenter.adapters.helper;
import android.content.Context;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
/**
* Created by tariel on 16/07/16.
*/
public class OnSwipeTouchListener implements View.OnTouchListener {
private final GestureDetector gestureDetector;
public OnSwipeTouchListener(Context context) {
gestureDetector = new GestureDetector(context, new GestureListener());
}
public void onSwipeLeft() {
}
public void onSwipeRight() {
}
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
private final class GestureListener extends GestureDetector.SimpleOnGestureListener {
private static final int SWIPE_DISTANCE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
float distanceX = e2.getX() - e1.getX();
float distanceY = e2.getY() - e1.getY();
if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (distanceX > 0)
onSwipeRight();
else
onSwipeLeft();
return true;
}
return false;
}
}
}

View File

@ -0,0 +1,15 @@
package com.hikapro.backpack.presenter.adapters.helper;
import android.content.Context;
import android.util.TypedValue;
/**
* Created by tariel on 10/07/16.
*/
public class Util {
public static int dp2px(Context context, int dp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
context.getResources().getDisplayMetrics());
}
}

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.presenter.adapters.helper.items;
package com.hikapro.backpack.presenter.adapters.helper.items;
import android.graphics.Rect;
import android.view.View;

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.presenter.adapters.helper.items;
package com.hikapro.backpack.presenter.adapters.helper.items;
import android.content.Context;
import android.content.res.TypedArray;
@ -9,6 +9,8 @@ import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.hikapro.backpack.presenter.adapters.helper.Util;
public class DividerDecoration extends RecyclerView.ItemDecoration {

View File

@ -0,0 +1,60 @@
package com.hikapro.backpack.presenter.adapters.helper.items;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* Created by tariel on 19/07/16.
*/
public class DividerDecoration2 extends RecyclerView.ItemDecoration {
private static final int[] ATTRS = new int[]{android.R.attr.listDivider};
private int paddingX;
private Drawable mDivider;
/**
* Default divider will be used
*/
public DividerDecoration2(Context context) {
final TypedArray styledAttributes = context.obtainStyledAttributes(ATTRS);
mDivider = styledAttributes.getDrawable(0);
styledAttributes.recycle();
}
/**
* Custom divider will be used
*/
public DividerDecoration2(Context context, int resId) {
mDivider = ContextCompat.getDrawable(context, resId);
}
public DividerDecoration2(Context context, int resId, int paddingX) {
mDivider = ContextCompat.getDrawable(context, resId);
this.paddingX = paddingX;
}
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
int left = parent.getPaddingLeft();
int right = parent.getWidth() - parent.getPaddingRight();
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
int top = child.getBottom() + params.bottomMargin;
int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left + paddingX, top, right - paddingX, bottom);
mDivider.draw(c);
}
}
}

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.presenter.adapters.helper.items;
package com.hikapro.backpack.presenter.adapters.helper.items;
import android.graphics.Rect;
import android.support.v7.widget.LinearLayoutManager;

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.presenter.adapters.helper.items;
package com.hikapro.backpack.presenter.adapters.helper.items;
import android.support.v7.widget.RecyclerView;
import android.view.View;

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.presenter.adapters.helper.items;
package com.hikapro.backpack.presenter.adapters.helper.items;
import android.graphics.Canvas;
import android.graphics.Rect;

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.presenter.adapters.helper.items;
package com.hikapro.backpack.presenter.adapters.helper.items;
import android.support.v4.util.LongSparseArray;
import android.support.v7.widget.RecyclerView;

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.presenter.adapters.helper.items;
package com.hikapro.backpack.presenter.adapters.helper.items;
import android.content.Context;
import android.graphics.Canvas;
@ -10,9 +10,10 @@ import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;
import android.view.ViewGroup;
import hikapro.com.backpack.R;
import hikapro.com.backpack.presenter.adapters.ItemListAdapter;
import com.hikapro.backpack.R;
import com.hikapro.backpack.presenter.adapters.ItemListAdapter;
/**
* Created by tariel on 02/05/16.
@ -21,6 +22,7 @@ public class ItemSwipeCallback extends ItemTouchHelper.SimpleCallback {
// we want to cache these and not allocate anything repeatedly in the onChildDraw method
Drawable background;
ViewGroup viewGroup;
Drawable xMark;
int xMarkMargin;
boolean initiated;
@ -50,22 +52,23 @@ public class ItemSwipeCallback extends ItemTouchHelper.SimpleCallback {
@Override
public int getSwipeDirs(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
int position = viewHolder.getAdapterPosition();
/*
if (adapter.isUndoOn() && adapter.isPendingRemoval(position)) {
return 0;
}
}*/
return super.getSwipeDirs(recyclerView, viewHolder);
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
int swipedPosition = viewHolder.getAdapterPosition();
/*
boolean undoOn = adapter.isUndoOn();
if (undoOn) {
adapter.pendingRemoval(swipedPosition);
} else {
adapter.remove(swipedPosition);
}
}*/
}
@Override
@ -82,11 +85,21 @@ public class ItemSwipeCallback extends ItemTouchHelper.SimpleCallback {
init();
}
if (-(c.getWidth() * 0.6) > dX) {
this.onChildDrawOver(c, recyclerView, viewHolder, dX, dY, actionState, false);
return;
}
// draw red background
background.setBounds(itemView.getRight() + (int) dX, itemView.getTop(), itemView.getRight(), itemView.getBottom());
background.draw(c);
//viewGroup.setLeft(itemView.getRight() + (int) dX);
//if ((itemView.getRight() + (int)dX) >= c.getWidth() * 0.6) {
background.setBounds(itemView.getRight() + (int) dX, itemView.getTop(), itemView.getRight(), itemView.getBottom());
background.draw(c);
//viewGroup.draw(c);
//}
// draw x mark
int itemHeight = itemView.getBottom() - itemView.getTop();
int intrinsicWidth = xMark.getIntrinsicWidth();
int intrinsicHeight = xMark.getIntrinsicWidth();

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.presenter.adapters.helper.items;
package com.hikapro.backpack.presenter.adapters.helper.items;
import android.graphics.Canvas;
import android.graphics.Color;

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.presenter.adapters.helper.items;
package com.hikapro.backpack.presenter.adapters.helper.items;
/**
* Created by tariel on 30/04/16.

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.presenter.adapters.helper.items;
package com.hikapro.backpack.presenter.adapters.helper.items;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.presenter.adapters.helper.items;
package com.hikapro.backpack.presenter.adapters.helper.items;
import android.graphics.Canvas;
import android.graphics.Rect;

View File

@ -0,0 +1,327 @@
package com.hikapro.backpack.presenter.adapters.helper.items.swipe2;
import android.content.Context;
import android.graphics.Rect;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.widget.ScrollerCompat;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.GestureDetector.OnGestureListener;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Interpolator;
import android.widget.LinearLayout;
/**
* Created by tariel on 18/06/16.
*/
public class SwipableElement extends LinearLayout {
public static final int DIRECTION_LEFT = 1;
public static final int DIRECTION_RIGHT = -1;
private static final int CONTENT_VIEW_ID = 1;
private static final int MENU_VIEW_ID = 2;
private static final int STATE_CLOSE = 0;
private static final int STATE_OPEN = 1;
private int mSwipeDirection;
private View mContentView;
private SwipeMenuLayout mMenuView;
private int mDownX;
private int state = STATE_CLOSE;
private GestureDetectorCompat mGestureDetector;
private OnGestureListener mGestureListener;
private boolean isFling;
private int MIN_FLING = dp2px(15);
private int MAX_VELOCITY_X = -dp2px(500);
private ScrollerCompat mOpenScroller;
private ScrollerCompat mCloseScroller;
private int mBaseX;
private Interpolator mCloseInterpolator;
private Interpolator mOpenInterpolator;
private boolean mSwipeEnable = true;
public SwipableElement(Context context, View contentView, SwipeMenuLayout menuView) {
this(context, contentView, menuView, null, null);
}
public SwipableElement(Context context, View contentView, SwipeMenuLayout menuView,
Interpolator closeInterpolator, Interpolator openInterpolator) {
super(context);
mCloseInterpolator = closeInterpolator;
mOpenInterpolator = openInterpolator;
mContentView = contentView;
mMenuView = menuView;
menuView.setSwipableElement(this);
doSomething();
}
private SwipableElement(Context context, AttributeSet attrs) {
super(context, attrs);
}
private SwipableElement(Context context) {
super(context);
}
public void setSwipeDirection(int swipeDirection) {
mSwipeDirection = swipeDirection;
}
private void doSomething() {
setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 56));
mGestureListener = new SimpleOnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
isFling = false;
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
if (e1 != null && e2 != null) {
if (Math.abs(e1.getX() - e2.getX()) > MIN_FLING
&& velocityX < MAX_VELOCITY_X) {
isFling = true;
}
}
return super.onFling(e1, e2, velocityX, velocityY);
}
};
mGestureDetector = new GestureDetectorCompat(getContext(), mGestureListener);
if (mCloseInterpolator != null) {
mCloseScroller = ScrollerCompat.create(getContext(),
mCloseInterpolator);
} else {
mCloseScroller = ScrollerCompat.create(getContext());
}
if (mOpenInterpolator != null) {
mOpenScroller = ScrollerCompat.create(getContext(),
mOpenInterpolator);
} else {
mOpenScroller = ScrollerCompat.create(getContext());
}
LayoutParams contentParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
mContentView.setLayoutParams(contentParams);
if (mContentView.getId() < 1) {
mContentView.setId(CONTENT_VIEW_ID);
}
if (mMenuView.getId() < 1)
mMenuView.setId(MENU_VIEW_ID);
mMenuView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
addView(mContentView);
addView(mMenuView);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
public boolean onSwipe(MotionEvent event) {
mGestureDetector.onTouchEvent(event);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mDownX = (int) event.getX();
isFling = false;
break;
case MotionEvent.ACTION_MOVE:
int dis = (int) (mDownX - event.getX());
if (state == STATE_OPEN) {
dis += mMenuView.getWidth() * mSwipeDirection;
}
swipe(dis);
break;
case MotionEvent.ACTION_UP:
if ((isFling || Math.abs(mDownX - event.getX()) > (mMenuView.getWidth() / 4)) &&
Math.signum(mDownX - event.getX()) == mSwipeDirection) {
smoothOpenMenu();
} else {
smoothCloseMenu();
return false;
}
break;
}
return true;
}
public boolean isOpen() {
return state == STATE_OPEN;
}
private void swipe(int dis) {
if (!mSwipeEnable){
return ;
}
if (Math.signum(dis) != mSwipeDirection) {
dis = 0;
} else if (mMenuView.getWidth() > 0 && Math.abs(dis) > mMenuView.getWidth()) {
dis = mMenuView.getWidth()*mSwipeDirection;
}
mContentView.layout(-dis, mContentView.getTop(),
mContentView.getWidth() -dis, getMeasuredHeight());
if (mSwipeDirection == SwipableRecycler.DIRECTION_LEFT) {
mMenuView.layout(mContentView.getWidth() - dis, mMenuView.getTop(),
mContentView.getWidth() + mMenuView.getWidth() - dis,
mMenuView.getBottom());
} else {
mMenuView.layout(-mMenuView.getWidth() - dis, mMenuView.getTop(),
- dis, mMenuView.getBottom());
}
}
@Override
public void computeScroll() {
if (state == STATE_OPEN) {
if (mOpenScroller.computeScrollOffset()) {
swipe(mOpenScroller.getCurrX()*mSwipeDirection);
postInvalidate();
}
} else {
if (mCloseScroller.computeScrollOffset()) {
swipe((mBaseX - mCloseScroller.getCurrX())*mSwipeDirection);
postInvalidate();
}
}
}
public void smoothCloseMenu() {
state = STATE_CLOSE;
if (mSwipeDirection == SwipableRecycler.DIRECTION_LEFT) {
mBaseX = -mContentView.getLeft();
mCloseScroller.startScroll(0, 0, mMenuView.getWidth(), 0, 350);
} else {
mBaseX = mMenuView.getRight();
mCloseScroller.startScroll(0, 0, mMenuView.getWidth(), 0, 350);
}
postInvalidate();
}
public void smoothOpenMenu() {
if(!mSwipeEnable){
return ;
}
state = STATE_OPEN;
if (mSwipeDirection == SwipableRecycler.DIRECTION_LEFT) {
mOpenScroller.startScroll(-mContentView.getLeft(), 0, mMenuView.getWidth(), 0, 350);
} else {
mOpenScroller.startScroll(mContentView.getLeft(), 0, mMenuView.getWidth(), 0, 350);
}
postInvalidate();
}
public void closeMenu() {
if (mCloseScroller.computeScrollOffset()) {
mCloseScroller.abortAnimation();
}
if (state == STATE_OPEN) {
state = STATE_CLOSE;
swipe(0);
}
}
public void openMenu() {
if(!mSwipeEnable){
return ;
}
if (state == STATE_CLOSE) {
state = STATE_OPEN;
swipe(mMenuView.getWidth() * mSwipeDirection);
}
}
public View getContentView() {
return mContentView;
}
public SwipeMenuLayout getMenuView() {
return mMenuView;
}
private int dp2px(int dp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
getContext().getResources().getDisplayMetrics());
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = getMeasuredWidth();
int height = getMeasuredHeight();
int childWidthMeasureSpec;
int childHeightMeasureSpec;
childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
mContentView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST);
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
mMenuView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
mContentView.layout(0, 0, getMeasuredWidth(),mContentView.getMeasuredHeight());
if (mSwipeDirection == DIRECTION_LEFT) {
mMenuView.layout(getMeasuredWidth(), 0,
getMeasuredWidth() + mMenuView.getMeasuredWidth(),
mContentView.getMeasuredHeight());
} else {
mMenuView.layout(-mMenuView.getMeasuredWidth(), 0,
0, mContentView.getMeasuredHeight());
}
}
public void setMenuHeight(int measuredHeight) {
LayoutParams params = (LayoutParams) mMenuView.getLayoutParams();
if (params.height != measuredHeight) {
params.height = measuredHeight;
mMenuView.setLayoutParams(mMenuView.getLayoutParams());
}
}
public void setSwipeEnable(boolean swipeEnable){
mSwipeEnable = swipeEnable;
}
public boolean getSwipeEnable(){
return mSwipeEnable;
}
public boolean isMenuVisible() {
Rect bounds = new Rect();
this.getHitRect(bounds);
if (mMenuView.getLocalVisibleRect(bounds)) {
return true;
} else {
return false;
}
}
}

View File

@ -0,0 +1,196 @@
package com.hikapro.backpack.presenter.adapters.helper.items.swipe2;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
/**
* Created by tariel on 06/07/16.
*/
public class SwipableRecycler extends RecyclerView {
private static final int TOUCH_ACTION_START = 1;
private static final int TOUCH_ACTION_MOVE_X = 2;
private static final int TOUCH_ACTION_MOVE_Y = 3;
public static final int DIRECTION_LEFT = 1;
public static final int DIRECTION_RIGHT = -1;
private int mDirection = 1; // swipe from right to left by default
private int MAX_Y = 5;
private int MAX_X = 3;
private float mDownX;
private float mDownY;
private int mTouchState;
private SwipableElement lastTouchedElement;
public SwipableRecycler(Context context) {
super(context);
init();
}
public SwipableRecycler(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public SwipableRecycler(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
View buf;
int action = e.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
boolean handled = false;
mDownX = e.getX();
mDownY = e.getY();
handled = super.onInterceptTouchEvent(e);
mTouchState = TOUCH_ACTION_START;
buf = findChildViewUnder(mDownX, mDownY);
if (buf instanceof SwipableElement) {
if (lastTouchedElement != null && lastTouchedElement.isOpen() && !inRangeOfView(lastTouchedElement.getMenuView(), e)) {
return true;
}
lastTouchedElement = (SwipableElement) buf;
lastTouchedElement.setSwipeDirection(mDirection);
}
if (lastTouchedElement != null && lastTouchedElement.isOpen() && lastTouchedElement != buf) {
handled = true;
}
if (lastTouchedElement != null)
lastTouchedElement.onSwipe(e);
return handled;
case MotionEvent.ACTION_MOVE:
float dy = Math.abs((e.getY() - mDownY));
float dx = Math.abs((e.getX() - mDownX));
if (Math.abs(dy) > MAX_Y || Math.abs(dx) > MAX_X) {
if (mTouchState == TOUCH_ACTION_START) {
if (Math.abs(dy) > MAX_Y) {
mTouchState = TOUCH_ACTION_MOVE_Y;
} else if (dx > MAX_X) {
mTouchState = TOUCH_ACTION_MOVE_X;
}
}
return true;
}
}
return super.onInterceptTouchEvent(e);
}
@Override
public boolean onTouchEvent(MotionEvent e) {
View buf;
int action = e.getAction();
if (action != MotionEvent.ACTION_DOWN && lastTouchedElement == null)
return super.onTouchEvent(e);
switch (action) {
case MotionEvent.ACTION_DOWN:
SwipableElement test = null;
mDownX = e.getX();
mDownY = e.getY();
mTouchState = TOUCH_ACTION_START;
buf = findChildViewUnder(e.getX(), e.getY());
if (buf instanceof SwipableElement)
test = (SwipableElement) buf;
if (lastTouchedElement != null && lastTouchedElement == test
&& lastTouchedElement.isOpen()) {
mTouchState = TOUCH_ACTION_MOVE_X;
lastTouchedElement.onSwipe(e);
return true;
}
if (lastTouchedElement != null && lastTouchedElement.isOpen()) {
lastTouchedElement.smoothCloseMenu();
lastTouchedElement = null;
// try to cancel the touch event
MotionEvent cancelEvent = MotionEvent.obtain(e);
cancelEvent.setAction(MotionEvent.ACTION_CANCEL);
super.onTouchEvent(cancelEvent);
return true;
}
if (buf instanceof SwipableElement) {
lastTouchedElement = (SwipableElement) buf;
lastTouchedElement.setSwipeDirection(mDirection);
}
if (lastTouchedElement != null) {
lastTouchedElement.onSwipe(e);
}
break;
case MotionEvent.ACTION_MOVE:
float dy = Math.abs((e.getY() - mDownY));
float dx = Math.abs((e.getX() - mDownX));
if (mTouchState == TOUCH_ACTION_MOVE_X) {
if (lastTouchedElement != null) {
lastTouchedElement.onSwipe(e);
}
e.setAction(MotionEvent.ACTION_CANCEL);
super.onTouchEvent(e);
return true;
} else if (mTouchState == TOUCH_ACTION_START) {
if (Math.abs(dy) > MAX_Y) {
mTouchState = TOUCH_ACTION_MOVE_Y;
} else if (dx > MAX_X) {
mTouchState = TOUCH_ACTION_MOVE_X;
}
}
break;
case MotionEvent.ACTION_UP:
if (mTouchState == TOUCH_ACTION_MOVE_X) {
if (lastTouchedElement != null) {
boolean isBeforeOpen = lastTouchedElement.isOpen();
lastTouchedElement.onSwipe(e);
boolean isAfterOpen = lastTouchedElement.isOpen();
if (!isAfterOpen) {
lastTouchedElement = null;
}
}
e.setAction(MotionEvent.ACTION_CANCEL);
super.onTouchEvent(e);
return true;
}
break;
}
return super.onTouchEvent(e);
}
public static boolean inRangeOfView(View view, MotionEvent ev) {
int[] location = new int[2];
view.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
if (ev.getRawX() < x || ev.getRawX() > (x + view.getWidth()) || ev.getRawY() < y || ev.getRawY() > (y + view.getHeight())) {
return false;
}
return true;
}
private void init() {
MAX_X = dp2px(MAX_X);
MAX_Y = dp2px(MAX_Y);
mTouchState = TOUCH_ACTION_START;
}
private int dp2px(int dp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
getContext().getResources().getDisplayMetrics());
}
}

View File

@ -0,0 +1,49 @@
package com.hikapro.backpack.presenter.adapters.helper.items.swipe2;
import android.content.Context;
import java.util.ArrayList;
import java.util.List;
/**
* Created by tariel on 18/06/16.
*/
public class SwipeMenu {
private Context mContext;
private List<SwipeMenuItem> mItems;
private int mViewType;
public SwipeMenu(Context context) {
mContext = context;
mItems = new ArrayList<SwipeMenuItem>();
}
public Context getContext() {
return mContext;
}
public void addMenuItem(SwipeMenuItem item) {
mItems.add(item);
}
public void removeMenuItem(SwipeMenuItem item) {
mItems.remove(item);
}
public List<SwipeMenuItem> getMenuItems() {
return mItems;
}
public SwipeMenuItem getMenuItem(int index) {
return mItems.get(index);
}
public int getViewType() {
return mViewType;
}
public void setViewType(int viewType) {
this.mViewType = viewType;
}
}

View File

@ -0,0 +1,91 @@
package com.hikapro.backpack.presenter.adapters.helper.items.swipe2;
import android.content.Context;
import android.graphics.drawable.Drawable;
/**
* Created by tariel on 18/06/16.
*/
public class SwipeMenuItem {
private int id;
private Context mContext;
private String title;
private Drawable icon;
private Drawable background;
private int titleColor;
private int titleSize;
private int width;
public SwipeMenuItem(Context context) {
mContext = context;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getTitleColor() {
return titleColor;
}
public int getTitleSize() {
return titleSize;
}
public void setTitleSize(int titleSize) {
this.titleSize = titleSize;
}
public void setTitleColor(int titleColor) {
this.titleColor = titleColor;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public void setTitle(int resId) {
setTitle(mContext.getString(resId));
}
public Drawable getIcon() {
return icon;
}
public void setIcon(Drawable icon) {
this.icon = icon;
}
public void setIcon(int resId) {
this.icon = mContext.getResources().getDrawable(resId);
}
public Drawable getBackground() {
return background;
}
public void setBackground(Drawable background) {
this.background = background;
}
public void setBackground(int resId) {
this.background = mContext.getResources().getDrawable(resId);
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
}

View File

@ -0,0 +1,140 @@
package com.hikapro.backpack.presenter.adapters.helper.items.swipe2;
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
/**
* Created by tariel on 18/06/16.
*/
public class SwipeMenuLayout extends LinearLayout {
private SwipeMenu swipeMenu;
private SwipableElement swipableElement;
public SwipeMenuLayout(Context context) {
super(context);
}
public SwipeMenuLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SwipeMenuLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setSwipableElement(SwipableElement swipableElement) {
this.swipableElement = swipableElement;
}
// adding menu with items
public void addMenu(SwipeMenu menu) {
swipeMenu = menu;
List<SwipeMenuItem> items = menu.getMenuItems();
int id = 0;
for (SwipeMenuItem item : items) {
addItem(item, item.getId() == 0 ? ++id : item.getId());
}
}
private void addItem(SwipeMenuItem item, int id) {
LayoutParams params = new LayoutParams(item.getWidth(),LayoutParams.MATCH_PARENT);
LinearLayout parent = new LinearLayout(getContext());
parent.setId(id);
parent.setGravity(Gravity.CENTER);
parent.setOrientation(LinearLayout.VERTICAL);
parent.setLayoutParams(params);
parent.setBackgroundDrawable(item.getBackground());
addView(parent);
if (item.getIcon() != null) {
parent.addView(createIcon(item));
}
if (!TextUtils.isEmpty(item.getTitle())) {
parent.addView(createTitle(item));
}
}
// adding menu with items + listener
public void addMenu(SwipeMenu menu, OnClickListener listener) {
swipeMenu = menu;
List<SwipeMenuItem> items = menu.getMenuItems();
int id = 0;
for (SwipeMenuItem item : items) {
addItem(item, item.getId() == 0 ? ++id : item.getId(), listener);
}
}
private void addItem(SwipeMenuItem item, int id, OnClickListener listener) {
LayoutParams params = new LayoutParams(item.getWidth(),LayoutParams.MATCH_PARENT);
LinearLayout parent = new LinearLayout(getContext());
parent.setId(id);
parent.setGravity(Gravity.CENTER);
parent.setOrientation(LinearLayout.VERTICAL);
parent.setLayoutParams(params);
parent.setBackgroundDrawable(item.getBackground());
parent.setOnClickListener(listener);
addView(parent);
if (item.getIcon() != null) {
parent.addView(createIcon(item));
}
if (!TextUtils.isEmpty(item.getTitle())) {
parent.addView(createTitle(item));
}
}
public void notifyOnMenuItemClick() {
if (swipableElement != null && swipableElement.isOpen())
swipableElement.smoothCloseMenu();
}
private ImageView createIcon(SwipeMenuItem item) {
ImageView iv = new ImageView(getContext());
iv.setImageDrawable(item.getIcon());
return iv;
}
private TextView createTitle(SwipeMenuItem item) {
TextView tv = new TextView(getContext());
tv.setText(item.getTitle());
tv.setGravity(Gravity.CENTER);
tv.setTextSize(item.getTitleSize());
tv.setTextColor(item.getTitleColor());
return tv;
}
private View findViewAtPoint(float x, float y) {
View ret = null;
View buf;
for (int i = 0; i < this.getChildCount(); ++i) {
buf = getChildAt(i);
if (isPointInsideView(x, y, buf)) {
ret = buf;
break;
}
}
return ret;
}
private boolean isPointInsideView(float x, float y, View view) {
int location[] = new int[2];
view.getLocationOnScreen(location);
int viewX = location[0];
int viewY = location[1];
// point is inside view bounds
return ((x > viewX && x < (viewX + view.getWidth())) &&
(y > viewY && y < (viewY + view.getHeight())));
}
}

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.presenter.adapters.helper.sets;
package com.hikapro.backpack.presenter.adapters.helper.sets;
/**
* Created by N551 on 25.04.2016.

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.presenter.adapters.helper.sets;
package com.hikapro.backpack.presenter.adapters.helper.sets;
/**
* Created by N551 on 25.04.2016.

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.presenter.adapters.helper.sets;
package com.hikapro.backpack.presenter.adapters.helper.sets;
import android.support.v7.widget.RecyclerView;

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.presenter.adapters.helper.sets;
package com.hikapro.backpack.presenter.adapters.helper.sets;
import android.graphics.Canvas;
import android.support.v7.widget.RecyclerView;

View File

@ -1,11 +1,12 @@
package hikapro.com.backpack.view;
package com.hikapro.backpack.view;
import android.content.Context;
import hikapro.com.backpack.model.entities.Item;
import hikapro.com.backpack.model.entities.Set;
import hikapro.com.backpack.presenter.Presenter;
import hikapro.com.backpack.presenter.adapters.helper.sets.OnStartDragListener;
import com.hikapro.backpack.model.Model;
import com.hikapro.backpack.model.entities.Item;
import com.hikapro.backpack.model.entities.Set;
import com.hikapro.backpack.presenter.Presenter;
import com.hikapro.backpack.presenter.adapters.helper.sets.OnStartDragListener;
/**
* Created by tariel on 19/04/16.
@ -25,21 +26,33 @@ public interface View {
}
interface ItemList extends Base {
void showItemDetail(Item item);
void showItemDetail(int setId, Model.Item baseModel, int position);
void showPackedItems(Set set);
void setPresenter(Presenter.ItemList presenter);
Set getSet();
}
interface ItemDetail extends Base {
void setPresenter(Presenter.ItemDetail presenter);
Item getItem();
int getSetId();
}
interface Share extends Base {
void setPresenter(Presenter.Share presenter);
}
interface Add extends Base {
void setPresenter(Presenter.Add presenter);
void setNewItem(Item item);
Set getSet();
}
interface ActivityCallback {
void startSetListFragment();
void startItemListFragment(Set set);
void startPackedListFragment(Set set);
void startItemDetailFragment(Item item);
void startItemDetailFragment(int setId, Model.Item baseModel, int position);
void startShareFragment(int setId);
void startAddFragment(Set set);
}
}

View File

@ -0,0 +1,160 @@
package com.hikapro.backpack.view.fragments;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SearchView;
import com.hikapro.backpack.R;
import com.hikapro.backpack.model.entities.Item;
import com.hikapro.backpack.model.entities.Set;
import com.hikapro.backpack.presenter.Presenter;
/**
* A simple {@link Fragment} subclass.
*/
public class AddFragment extends Fragment implements com.hikapro.backpack.view.View.Add {
protected static final String BUNDLE_SET_KEY = "BUNDLE_SET_KEY";
private Presenter.Add presenter;
private com.hikapro.backpack.view.View.ActivityCallback activityCallback;
public static AddFragment construct() {
return new AddFragment();
}
public static AddFragment newFromSet(Set set) {
AddFragment ret = AddFragment.construct();
Bundle args = new Bundle();
args.putSerializable(BUNDLE_SET_KEY, set);
ret.setArguments(args);
return ret;
}
public AddFragment() {
// Required empty public constructor
}
// life cycle -->
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
activityCallback = (com.hikapro.backpack.view.View.ActivityCallback) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement activityCallback");
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
activityCallback = (com.hikapro.backpack.view.View.ActivityCallback) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement activityCallback");
}
Log.i(this.toString(), " onAttach");
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setHasOptionsMenu(true);
Log.i(this.toString(), " onCreate");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
presenter.setView(this);
View view = presenter.onCreateView(inflater, container, savedInstanceState);
Log.i(this.toString(), " onCreateView");
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i(this.toString(), " onActivityCreated");
}
@Override
public void onStart() {
super.onStart();
Log.i(this.toString(), " onStart");
}
@Override
public void onResume() {
super.onResume();
Log.i(this.toString(), " onResume");
}
@Override
public void onStop() {
super.onStop();
Log.i(this.toString(), " onStop");
}
@Override
public void onDestroyView() {
super.onDestroyView();
presenter.onDestroy(true); // TODO isChangingConfigurations
Log.i(this.toString(), " onDestroyView");
}
@Override
public void onDestroy() {
super.onDestroy();
presenter.onDestroy(false); // TODO isChangingConfigurations
Log.i(this.toString(), " onDestroy");
}
@Override
public void onDetach() {
super.onDetach();
Log.i(this.toString(), " onDetach");
}
@Override
public Context getAppContext() {
return this.getActivity().getApplicationContext();
}
@Override
public Context getActivityContext() {
return this.getActivity();
}
@Override
public void setPresenter(Presenter.Add presenter) {
this.presenter = presenter;
}
@Override
public void setNewItem(Item item) {
}
public Set getSet() {
return (Set) getArguments().getSerializable(BUNDLE_SET_KEY);
}
/*
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_add, menu);
super.onCreateOptionsMenu(menu, inflater);
}
*/
}

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.view.fragments;
package com.hikapro.backpack.view.fragments;
import android.app.Activity;
@ -7,21 +7,25 @@ import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import hikapro.com.backpack.model.entities.Item;
import hikapro.com.backpack.presenter.Presenter;
import com.hikapro.backpack.R;
import com.hikapro.backpack.model.entities.Item;
import com.hikapro.backpack.presenter.Presenter;
/**
* A simple {@link Fragment} subclass.
*/
public class ItemDetailFragment extends Fragment implements hikapro.com.backpack.view.View.ItemDetail {
public class ItemDetailFragment extends Fragment implements com.hikapro.backpack.view.View.ItemDetail {
private static final String BUNDLE_ITEM_KEY = "BUNDLE_ITEM_KEY";
private static final String BUNDLE_SET_KEY = "BUNDLE_SET_KEY";
private Presenter.ItemDetail presenter;
private hikapro.com.backpack.view.View.ActivityCallback activityCallback;
private com.hikapro.backpack.view.View.ActivityCallback activityCallback;
public ItemDetailFragment() {
@ -32,10 +36,10 @@ public class ItemDetailFragment extends Fragment implements hikapro.com.backpack
return new ItemDetailFragment();
}
public static ItemDetailFragment newFromItem(Item item) {
public static ItemDetailFragment newInstance(int setId) {
ItemDetailFragment ret = ItemDetailFragment.construct();
Bundle args = new Bundle();
args.putSerializable(BUNDLE_ITEM_KEY, item);
args.putInt(BUNDLE_SET_KEY, setId);
ret.setArguments(args);
return ret;
}
@ -45,7 +49,7 @@ public class ItemDetailFragment extends Fragment implements hikapro.com.backpack
public void onAttach(Context context) {
super.onAttach(context);
try {
activityCallback = (hikapro.com.backpack.view.View.ActivityCallback) context;
activityCallback = (com.hikapro.backpack.view.View.ActivityCallback) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement activityCallback");
@ -55,7 +59,7 @@ public class ItemDetailFragment extends Fragment implements hikapro.com.backpack
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
activityCallback = (hikapro.com.backpack.view.View.ActivityCallback) activity;
activityCallback = (com.hikapro.backpack.view.View.ActivityCallback) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement activityCallback");
@ -137,9 +141,9 @@ public class ItemDetailFragment extends Fragment implements hikapro.com.backpack
}
@Override
public Item getItem() {
public int getSetId() {
Bundle args = getArguments();
Item item = (Item) args.getSerializable(BUNDLE_ITEM_KEY);
return item;
int setId = args.getInt(BUNDLE_SET_KEY);
return setId;
}
}

View File

@ -1,10 +1,11 @@
package hikapro.com.backpack.view.fragments;
package com.hikapro.backpack.view.fragments;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
@ -15,18 +16,18 @@ import android.view.ViewGroup;
import android.widget.SearchView;
import android.widget.Toast;
import hikapro.com.backpack.R;
import hikapro.com.backpack.model.entities.Item;
import hikapro.com.backpack.model.entities.Set;
import hikapro.com.backpack.presenter.ItemListPresenter;
import hikapro.com.backpack.presenter.Presenter;
import com.hikapro.backpack.R;
import com.hikapro.backpack.model.Model;
import com.hikapro.backpack.model.entities.Item;
import com.hikapro.backpack.model.entities.Set;
import com.hikapro.backpack.presenter.Presenter;
public class ItemListFragment extends Fragment implements hikapro.com.backpack.view.View.ItemList,
public class ItemListFragment extends Fragment implements com.hikapro.backpack.view.View.ItemList,
SearchView.OnQueryTextListener {
protected static final String BUNDLE_SET_KEY = "BUNDLE_SET_KEY";
private hikapro.com.backpack.view.View.ActivityCallback activityCallback;
private com.hikapro.backpack.view.View.ActivityCallback activityCallback;
private Presenter.ItemList presenter;
public ItemListFragment() {
@ -71,19 +72,24 @@ public class ItemListFragment extends Fragment implements hikapro.com.backpack.v
@Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean ret;
switch (item.getItemId()) {
case R.id.action_share :
Toast.makeText(getActivityContext(), "Share", Toast.LENGTH_SHORT).show();
activityCallback.startShareFragment(getSet().getId());
ret = true;
break;
case R.id.action_unpack_my_bag :
Toast.makeText(getActivityContext(), "Unpack my bag", Toast.LENGTH_SHORT).show();
presenter.unpack(getSet().getId());
ret = true;
break;
case R.id.action_restore_to_default :
Toast.makeText(getActivityContext(), "Restore to default", Toast.LENGTH_SHORT).show();
presenter.restore(getSet().getId());
ret = true;
break;
case R.id.action_add :
activityCallback.startAddFragment(getSet());
ret = true;
default:
ret = super.onOptionsItemSelected(item);
}
@ -95,7 +101,7 @@ public class ItemListFragment extends Fragment implements hikapro.com.backpack.v
public void onAttach(Context context) {
super.onAttach(context);
try {
activityCallback = (hikapro.com.backpack.view.View.ActivityCallback) context;
activityCallback = (com.hikapro.backpack.view.View.ActivityCallback) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement activityCallback");
@ -105,18 +111,18 @@ public class ItemListFragment extends Fragment implements hikapro.com.backpack.v
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
activityCallback = (hikapro.com.backpack.view.View.ActivityCallback) activity;
activityCallback = (com.hikapro.backpack.view.View.ActivityCallback) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement activityCallback");
}
Log.i(this.toString(), " onAttach");
Log.i(this.getClass().getName(), " onAttach");
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
Log.i(this.toString(), " onCreate");
Log.i(this.getClass().getName(), " onCreate");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
@ -124,58 +130,59 @@ public class ItemListFragment extends Fragment implements hikapro.com.backpack.v
// Inflate the layout for this fragment
presenter.setView(this);
View view = presenter.onCreateView(inflater, container, savedInstanceState);
Log.i(this.toString(), " onCreateView");
Log.i(this.getClass().getName(), " onCreateView");
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i(this.toString(), " onActivityCreated");
Log.i(this.getClass().getName(), " onActivityCreated");
}
@Override
public void onStart() {
super.onStart();
Log.i(this.toString(), " onStart");
Log.i(this.getClass().getName(), " onStart");
}
@Override
public void onResume() {
super.onResume();
Log.i(this.toString(), " onResume");
Log.i(this.getClass().getName(), " onResume");
}
@Override
public void onStop() {
super.onStop();
Log.i(this.toString(), " onStop");
Log.i(this.getClass().getName(), " onStop");
}
@Override
public void onDestroyView() {
super.onDestroyView();
presenter.onDestroy(true); // TODO isChangingConfigurations
Log.i(this.toString(), " onDestroyView");
Log.i(this.getClass().getName(), " onDestroyView");
}
@Override
public void onDestroy() {
super.onDestroy();
presenter.onDestroy(false); // TODO isChangingConfigurations
Log.i(this.toString(), " onDestroy");
Log.i(this.getClass().getName(), " onDestroy");
}
@Override
public void onDetach() {
super.onDetach();
Log.i(this.toString(), " onDetach");
Log.i(this.getClass().getName(), " onDetach");
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
presenter.onSaveInstanceState(outState);
Log.i(this.toString(), " onSaveInstanceState");
Log.i(this.getClass().getName(), " onSaveInstanceState");
}
// life cycle <--
@Override
public void showItemDetail(Item item) {
activityCallback.startItemDetailFragment(item);
public void showItemDetail(int setId, Model.Item baseModel, int position) {
activityCallback.startItemDetailFragment(setId, baseModel, position);
}
@Override

View File

@ -1,8 +1,8 @@
package hikapro.com.backpack.view.fragments;
package com.hikapro.backpack.view.fragments;
import android.os.Bundle;
import hikapro.com.backpack.model.entities.Set;
import com.hikapro.backpack.model.entities.Set;
/**
* Created by tariel on 12/05/16.

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.view.fragments;
package com.hikapro.backpack.view.fragments;
import android.app.Activity;
import android.app.Fragment;
@ -10,15 +10,15 @@ import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import hikapro.com.backpack.model.entities.Set;
import hikapro.com.backpack.presenter.Presenter;
import hikapro.com.backpack.presenter.adapters.helper.sets.OnStartDragListener;
import com.hikapro.backpack.model.entities.Set;
import com.hikapro.backpack.presenter.Presenter;
import com.hikapro.backpack.presenter.adapters.helper.sets.OnStartDragListener;
public class SetListFragment extends Fragment implements hikapro.com.backpack.view.View.SetList,
public class SetListFragment extends Fragment implements com.hikapro.backpack.view.View.SetList,
OnStartDragListener {
private Presenter.SetList presenter;
private hikapro.com.backpack.view.View.ActivityCallback activityCallback;
private com.hikapro.backpack.view.View.ActivityCallback activityCallback;
public SetListFragment() {
@ -34,7 +34,7 @@ public class SetListFragment extends Fragment implements hikapro.com.backpack.vi
public void onAttach(Context context) {
super.onAttach(context);
try {
activityCallback = (hikapro.com.backpack.view.View.ActivityCallback) context;
activityCallback = (com.hikapro.backpack.view.View.ActivityCallback) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement activityCallback");
@ -44,7 +44,7 @@ public class SetListFragment extends Fragment implements hikapro.com.backpack.vi
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
activityCallback = (hikapro.com.backpack.view.View.ActivityCallback) activity;
activityCallback = (com.hikapro.backpack.view.View.ActivityCallback) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement activityCallback");
@ -113,7 +113,10 @@ public class SetListFragment extends Fragment implements hikapro.com.backpack.vi
@Override
public void showItemList(Set set) {
activityCallback.startItemListFragment(set);
if (set.getActiveQty() == set.getPackedQty())
activityCallback.startPackedListFragment(set);
else
activityCallback.startItemListFragment(set);
}
@Override

View File

@ -0,0 +1,79 @@
package com.hikapro.backpack.view.fragments;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.hikapro.backpack.R;
import com.hikapro.backpack.presenter.Presenter;
/**
* A simple {@link Fragment} subclass.
*/
public class ShareFragment extends Fragment implements com.hikapro.backpack.view.View.Share {
private Presenter.Share presenter;
private com.hikapro.backpack.view.View.ActivityCallback activityCallback;
public ShareFragment() {
// Required empty public constructor
}
public static ShareFragment construct() {
ShareFragment ret = new ShareFragment();
return ret;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
activityCallback = (com.hikapro.backpack.view.View.ActivityCallback) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement activityCallback");
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
activityCallback = (com.hikapro.backpack.view.View.ActivityCallback) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement activityCallback");
}
Log.i(this.toString(), "onAttach");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
presenter.setView(this);
View v = presenter.onCreateView(inflater, container, savedInstanceState);
return v;
}
@Override
public void setPresenter(Presenter.Share presenter) {
this.presenter = presenter;
}
@Override
public Context getAppContext() {
return this.getActivity().getApplicationContext();
}
@Override
public Context getActivityContext() {
return this.getActivity();
}
}

View File

@ -0,0 +1,32 @@
package com.hikapro.backpack.view.recycler;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.hikapro.backpack.R;
/**
* Created by tariel on 18/05/16.
*/
public class AddItemViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public TextView category;
public TextView alreadyInList;
public RelativeLayout item;
public AddItemViewHolder(View itemView) {
super(itemView);
setupViews(itemView);
}
private void setupViews(View view) {
item = (RelativeLayout) view.findViewById(R.id.add_item_item);
name = (TextView) item.findViewById(R.id.add_item_name);
category = (TextView) item.findViewById(R.id.add_item_category);
alreadyInList = (TextView) item.findViewById(R.id.add_already_in_list);
}
}

View File

@ -1,10 +1,10 @@
package hikapro.com.backpack.view.recycler;
package com.hikapro.backpack.view.recycler;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import hikapro.com.backpack.R;
import com.hikapro.backpack.R;
/**
* Created by tariel on 01/05/16.

View File

@ -0,0 +1,37 @@
package com.hikapro.backpack.view.recycler;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.TextView;
import com.hikapro.backpack.R;
import com.hikapro.backpack.presenter.adapters.helper.items.swipe2.SwipableElement;
/**
* Created by tariel on 01/05/16.
*/
public class ItemViewHolder extends RecyclerView.ViewHolder {
public CheckBox cb_item;
public TextView tv_text;
public ImageButton im_info;
public ViewGroup menu;
public ItemViewHolder(View v) {
super(v);
setupViews(v);
}
private void setupViews(View view) {
cb_item = (CheckBox) view.findViewById(R.id.item_checkbox);
tv_text = (TextView) view.findViewById(R.id.item_text);
im_info = (ImageButton) view.findViewById(R.id.item_info_button);
menu = (ViewGroup) view.findViewById(R.id.menu);
}
}

View File

@ -1,4 +1,4 @@
package hikapro.com.backpack.view.recycler;
package com.hikapro.backpack.view.recycler;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
@ -7,8 +7,8 @@ import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import hikapro.com.backpack.R;
import hikapro.com.backpack.presenter.adapters.helper.sets.ItemTouchHelperViewHolder;
import com.hikapro.backpack.R;
import com.hikapro.backpack.presenter.adapters.helper.sets.ItemTouchHelperViewHolder;
/**
* Created by tariel on 20/04/16.

View File

@ -1,36 +0,0 @@
package hikapro.com.backpack.model;
import java.util.List;
import hikapro.com.backpack.model.entities.Category;
import hikapro.com.backpack.model.entities.Item;
import hikapro.com.backpack.model.entities.Set;
import hikapro.com.backpack.model.entities.Timestamp;
import hikapro.com.backpack.model.entities.Updates;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
/**
* Created by tariel on 19/04/16.
*/
public interface Api {
@GET("api/v1/backpack/items")
Call<List<Item>> getItems();
@GET("api/v1/backpack/item_categories")
Call<List<Category>> getItemCategories();
@GET("api/v1/backpack/sets")
Call<List<Set>> getSets();
@GET("api/v1/backpack/updates/timestamp")
Call<Timestamp> getTimestamp();
@GET("api/v1/backpack/updates/all")
Call<Updates> getUpdates(@Query("timestamp") long timestamp);
}

View File

@ -1,105 +0,0 @@
package hikapro.com.backpack.model;
import android.graphics.Bitmap;
import android.os.Message;
import java.util.List;
import hikapro.com.backpack.model.dao.Command;
import hikapro.com.backpack.model.dao.DAO;
import hikapro.com.backpack.model.dao.Event;
import hikapro.com.backpack.model.entities.Item;
import hikapro.com.backpack.model.entities.Set;
import hikapro.com.backpack.presenter.Presenter;
/**
* Created by tariel on 23/04/16.
*/
public class DetailModel implements Model.Detail {
private Presenter.ItemDetail presenter;
private Item item;
private DAO dao;
private Bitmap pic;
public DetailModel() {
this.dao = DAO.getInstance();
dao.registerObserver(this);
}
// detail -->
@Override
public int getCount() {
return 1;
}
@Override
public Item findItem(int id) {
return item;
}
@Override
public Bitmap getPicture() {
return pic;
}
// detail <--
// events -->
@Override
public void notifyDataSetChanged() {
presenter.notifyDataSetChanged();
}
@Override
public void onDestroy(boolean isConfigurationChanging) {
if ( !isConfigurationChanging ) {
presenter = null;
}
}
private void sendMessage(String message) {
presenter.showMessage(message);
}
// events <--
// process -->
@Override
public void executeQuery() {
notifyDataSetChanged();
Message command;
command = Message.obtain();
command.what = Command.ITEM_GET_IMAGE;
command.arg1 = item.getId();
dao.executeCommand(command);
}
// process <--
@Override
public void setPresenter(Presenter.ItemDetail presenter) {
this.presenter = presenter;
this.item = presenter.getCurrentItem();
}
@Override
public Presenter.ItemDetail getPresenter() {
return presenter;
}
@Override
public void onEvent(Message event) {
switch (event.what) {
case Event.ITEM_IMAGE_LOAD_ERROR :
break;
case Event.ITEM_IMAGE_LOAD_COMPLETED :
pic = (Bitmap) event.obj;
notifyDataSetChanged();
break;
}
}
}

View File

@ -1,345 +0,0 @@
package hikapro.com.backpack.model;
import android.os.Message;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import hikapro.com.backpack.model.dao.Command;
import hikapro.com.backpack.model.dao.DAO;
import hikapro.com.backpack.model.dao.Event;
import hikapro.com.backpack.model.entities.Category;
import hikapro.com.backpack.model.entities.Item;
import hikapro.com.backpack.presenter.Presenter;
/**
* Created by tariel on 22/04/16.
*/
public class ItemModel implements Model.Item {
protected Presenter.ItemList presenter;
private List<Category> rawCategories;
private List<Category> sortedCategories;
private List<Item> rawItems;
protected DAO dao;
protected int currentSet;
protected int currentSetActiveItemsQty;
protected int packedQty;
protected Hashtable<Integer, Category> categoriesCache;
private List<Item> itemsCache;
private List<Item> itemsDiscardCache;
private Hashtable<Category, List<Item>> items;
protected Hashtable<Integer, List<Item>> cache;
public ItemModel() {
this.rawCategories = new ArrayList<>();
this.rawItems = new ArrayList<>();
this.sortedCategories = new ArrayList<>();
this.categoriesCache = new Hashtable<>(20, 0.9f);
this.packedQty = -1;
this.itemsCache = new ArrayList<>();
this.itemsDiscardCache = new ArrayList<>();
this.cache = new Hashtable<>(12, 0.9f);
this.dao = DAO.getInstance();
dao.registerObserver(this);
}
// categories -->
@Override
public Category getCategoryByPosition(int position) {
Category ret = null;
if (cache.containsKey(currentSet))
ret = categoriesCache.get(cache.get(currentSet).get(position).getCategory());
return ret;
}
// categories <--
// items -->
@Override
public int insertItem(Item item) {
List<Item> iList = cache.get(currentSet);
iList.add(item);
Collections.sort(iList);
cache.put(currentSet, iList);
++currentSetActiveItemsQty;
// TODO write to database
return 0;
}
@Override
public boolean deleteItem(Item item) {
if (isPendingRemoval(item))
itemsDiscardCache.remove(item);
cache.get(currentSet).remove(item);
--currentSetActiveItemsQty;
//TODO write to ds
return false;
}
@Override
public Item findItem(int id) {
List<Item> items = cache.get(currentSet);
Item item = null;
if (items != null)
{
for (Item i : items) {
if (i.getId() == id) {
item = i;
break;
}
}
}
return item;
}
@Override
public Item getItemByPosition(int position) {
Item ret = null;
if (cache.containsKey(currentSet))
ret = cache.get(currentSet).get(position);
return ret;
}
@Override
public void filter(String query) {
if (query.isEmpty()) {
Message command = Message.obtain();
command.what = Command.SET_GET_ITEMS;
command.arg1 = presenter.getCurrentSet().getId();
dao.executeCommand(command);
} else {
query = query.toLowerCase();
String name;
List<Item> newList = new ArrayList<>(20);
List<Item> oldList = cache.get(currentSet);
for (Item item : oldList) {
name = item.getName().toLowerCase();
if (name.contains(query)) {
newList.add(item);
}
}
cache.put(currentSet, newList);
}
}
@Override
public int getHeaderId(int position) {
return cache.containsKey(currentSet) ? cache.get(currentSet).get(position).getCategory() : -1;
}
@Override
public int getItemId(int position) {
return cache.containsKey(currentSet) ? cache.get(currentSet).get(position).getId() : -1;
}
@Override
public void clear() {
if (cache.containsKey(currentSet))
cache.get(currentSet).clear();
}
@Override
public boolean isPendingRemoval(Item item) {
return itemsDiscardCache.contains(item);
}
@Override
public void pendingRemoveCancel(Item item) {
if (itemsDiscardCache.contains(item))
itemsDiscardCache.remove(item);
}
@Override
public void pendingRemove(Item item) {
itemsDiscardCache.add(item);
}
@Override
public int getItemsCount() {
boolean is = cache.containsKey(currentSet);
return is ? cache.get(currentSet).size() : 0;
}
@Override
public int getActiveItemsCount() {
return currentSetActiveItemsQty;
}
@Override
public int getPackedQty() {
return packedQty;
}
// items <--
// events -->
@Override
public void notifyDataSetChanged() {
presenter.notifyDataSetChanged();
}
@Override
public void onDestroy(boolean isConfigurationChanging) {
if ( !isConfigurationChanging ) {
presenter = null;
}
}
private void sendMessage(String message) {
presenter.showMessage(message);
}
// events <--
// process -->
@Override
public void packItem(int itemId) {
Item item = findItem(itemId);
if (item != null)
cache.get(currentSet).remove(item);
Message command = Message.obtain();
command.what = Command.ITEM_PACK;
command.arg1 = currentSet;
command.arg2 = itemId;
dao.executeCommand(command);
}
@Override
public void unpackItem(int itemId) {
// nothing
}
@Override
public void unpackSet(int setId) {
// nothing
}
@Override
public void executeQuery() {
Message command;
if (cache.contains(currentSet)) {
notifyDataSetChanged();
} else {
if (categoriesCache.isEmpty()) {
command = Message.obtain();
command.what = Command.ITEM_GET_CATEGORIES;
dao.executeCommand(command);
}
command = Message.obtain();
command.what = Command.SET_GET_ITEMS;
command.arg1 = presenter.getCurrentSet().getId();
dao.executeCommand(command);
}
}
@Override
public void onEvent(Message event) {
switch (event.what) {
case Event.SET_ITEMS_LOAD_ERROR : // TODO check
if (presenter != null) {
if (packedQty == -1)
packedQty = presenter.getCurrentSet().getPackedQty();
presenter.notifyItemPackStatusChanged();
}
break;
case Event.SET_UNPACK_ERROR :
break;
case Event.ITEM_FROM_SET_ERROR :
break;
case Event.ITEM_DELETE_ERROR :
break;
case Event.ITEM_PACK_ERROR :
break;
case Event.ITEM_UNPACK_ERROR :
break;
case Event.ITEM_INSERT_ERROR :
break;
case Event.ITEM_CATEGORY_LOAD_ERROR :
break;
case Event.SET_ITEMS_LOAD_COMPLETED :
List<Item> res = (List<Item>) event.obj;
cache.put(event.arg1, res);
notifyDataSetChanged();
if (presenter != null) {
if (packedQty == -1)
packedQty = presenter.getCurrentSet().getPackedQty();
presenter.notifyItemPackStatusChanged();
}
break;
case Event.SET_UNPACK_COMPLETED :
packedQty = 0;
if (presenter != null) {
presenter.notifyItemPackStatusChanged();
}
break;
case Event.ITEM_CATEGORY_LOAD_COMPLETED :
categoriesCache = (Hashtable<Integer, Category>)event.obj;
break;
case Event.ITEM_FROM_SET_DELETED :
break;
case Event.ITEM_DELETED :
break;
case Event.ITEM_PACKED :
//TODO something
++packedQty;
if (presenter != null) {
presenter.notifyItemPackStatusChanged();
}
break;
case Event.ITEM_UNPACKED :
--packedQty;
if (presenter != null) {
presenter.notifyItemPackStatusChanged();
}
break;
case Event.ITEM_INSERTED :
break;
}
}
// process <--
// other -->
@Override
public void setPresenter(Presenter.ItemList presenter) {
this.presenter = presenter;
this.currentSet = presenter.getCurrentSet().getId();
this.currentSetActiveItemsQty = presenter.getCurrentSet().getActiveQty();
}
@Override
public Presenter.ItemList getPresenter() {
return presenter;
}
private Category findCategory(int categoryId) {
Category category = null;
for (Category c : rawCategories) {
if (c.getId() == categoryId) {
category = c;
break;
}
}
return category;
}
// other <--
}

View File

@ -1,72 +0,0 @@
package hikapro.com.backpack.model;
import android.graphics.Bitmap;
import android.os.Message;
import java.util.List;
import hikapro.com.backpack.model.entities.Category;
import hikapro.com.backpack.model.entities.Item;
import hikapro.com.backpack.model.entities.Set;
import hikapro.com.backpack.presenter.Presenter;
/**
* Created by tariel on 19/04/16.
*/
public interface Model {
interface Base {
void onDestroy(boolean isConfigurationChanging);
void executeQuery();
void notifyDataSetChanged();
void onEvent(Message event);
}
interface Set extends Base {
hikapro.com.backpack.model.entities.Set getSetByPosition(int position);
hikapro.com.backpack.model.entities.Set findSet(int id);
int getSetsCount();
void setPresenter(Presenter.SetList presenter);
Presenter.SetList getPresenter();
//GLM
List<hikapro.com.backpack.model.entities.Set> getSets(); // tag renamed
void setsReorderNotify();
}
interface Item extends Base {
int insertItem(hikapro.com.backpack.model.entities.Item item);
boolean deleteItem(hikapro.com.backpack.model.entities.Item item);
void filter(String query);
int getHeaderId(int position);//TODO review
int getItemId(int position);//TODO review
void clear();
boolean isPendingRemoval(hikapro.com.backpack.model.entities.Item item);
void pendingRemove(hikapro.com.backpack.model.entities.Item item);
void pendingRemoveCancel(hikapro.com.backpack.model.entities.Item item);
int getItemsCount();
int getActiveItemsCount();
int getPackedQty();
hikapro.com.backpack.model.entities.Item findItem(int id);
hikapro.com.backpack.model.entities.Item getItemByPosition(int position);
hikapro.com.backpack.model.entities.Category getCategoryByPosition(int position);
void setPresenter(Presenter.ItemList presenter);
Presenter.ItemList getPresenter();
void packItem(int itemId);
void unpackItem(int itemId);
void unpackSet(int setId);
}
interface Detail extends Base {
int getCount();
hikapro.com.backpack.model.entities.Item findItem(int id);
Bitmap getPicture();
void setPresenter(Presenter.ItemDetail presenter);
Presenter.ItemDetail getPresenter();
}
}

View File

@ -1,121 +0,0 @@
package hikapro.com.backpack.model;
import android.os.Message;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import hikapro.com.backpack.model.dao.Command;
import hikapro.com.backpack.model.dao.DAO;
import hikapro.com.backpack.model.dao.Event;
import hikapro.com.backpack.model.entities.Category;
import hikapro.com.backpack.model.entities.Item;
import hikapro.com.backpack.presenter.Presenter;
/**
* Created by tariel on 12/05/16.
*/
public class PackedModel extends ItemModel {
public PackedModel() {
super();
}
@Override
public void executeQuery() {
Message command;
if (cache.contains(currentSet)) {
notifyDataSetChanged();
} else {
if (categoriesCache.isEmpty()) {
command = Message.obtain();
command.what = Command.ITEM_GET_CATEGORIES;
dao.executeCommand(command);
}
command = Message.obtain();
command.what = Command.SET_GET_PACKED_ITEMS;
command.arg1 = presenter.getCurrentSet().getId();
dao.executeCommand(command);
}
}
@Override
public void onEvent(Message event) {
switch (event.what) {
case Event.SET_PACKED_LOAD_ERROR :
break;
case Event.SET_UNPACK_ERROR :
break;
case Event.ITEM_CATEGORY_LOAD_ERROR :
break;
case Event.ITEM_PACK_ERROR :
break;
case Event.ITEM_UNPACK_ERROR :
break;
case Event.SET_PACKED_LOAD_COMPLETED :
List<Item> res = (List<Item>) event.obj;
cache.put(event.arg1, res);
notifyDataSetChanged();
packedQty = res.size();
if (presenter != null) {
presenter.notifyItemPackStatusChanged();
}
break;
case Event.SET_UNPACK_COMPLETED :
packedQty = 0;
cache.get(event.arg2).clear();
if (presenter != null) {
presenter.notifyItemPackStatusChanged();
}
break;
case Event.ITEM_CATEGORY_LOAD_COMPLETED :
categoriesCache = (Hashtable<Integer, Category>)event.obj;
break;
case Event.ITEM_PACKED :
//TODO something
++packedQty;
if (presenter != null) {
presenter.notifyItemPackStatusChanged();
}
break;
case Event.ITEM_UNPACKED :
--packedQty;
if (presenter != null) {
presenter.notifyItemPackStatusChanged();
}
break;
}
}
@Override
public void unpackItem(int itemId) {
Message command;
command = Message.obtain();
command.what = Command.ITEM_UNPACK;
command.arg1 = currentSet;
command.arg2 = itemId;
dao.executeCommand(command);
Item item = findItem(itemId);
if (item != null)
cache.get(currentSet).remove(item);
}
@Override
public void packItem(int itemId) {
// nothing
}
@Override
public void unpackSet(int setId) {
Message command;
command = Message.obtain();
command.what = Command.SET_UNPACK_ITEMS;
command.arg1 = setId;
dao.executeCommand(command);
}
}

View File

@ -1,966 +0,0 @@
package hikapro.com.backpack.model.dao;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import hikapro.com.backpack.App;
import hikapro.com.backpack.model.Api;
import hikapro.com.backpack.model.Model;
import hikapro.com.backpack.model.RestClient;
import hikapro.com.backpack.model.SetModel;
import hikapro.com.backpack.model.entities.Category;
import hikapro.com.backpack.model.entities.Item;
import hikapro.com.backpack.model.entities.Set;
import hikapro.com.backpack.model.entities.Timestamp;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by tariel on 20/04/16.
*/
public class DAO {
//region Constants
private static final int CORE_POOL_SIZE = 1;
private static final int CORE_MAX_POOL_SIZE = 1;
private static final int KEEP_ALIVE_TIME = 1;
private static final TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;
private static final int MY_LIST_ID = 15;
//endregion
private static DAO instance;
private final ThreadPoolExecutor threadPool;
private final Handler handler;
private SetModel setModel;
private final Api api;
private Context context;
private DbHelper helper;
private Map<String, Model.Base> observers;
private DAO() {
this.context = App.getAppContext();
this.helper = new DbHelper(this.context);
this.api = RestClient.getApi();
final BlockingQueue<Runnable> taskQueue = new LinkedBlockingQueue<>();
this.threadPool = initPool(taskQueue);
this.observers = Collections.synchronizedMap(new HashMap<String, Model.Base>());
this.handler = initHandler();
}
static {
instance = new DAO();
}
public static DAO getInstance() {
return instance;
}
public void registerObserver(Model.Base o) {
observers.put(o.getClass().getName(), o);
}
private ThreadPoolExecutor initPool (BlockingQueue<Runnable> taskQueue) {
ThreadPoolExecutor ret = new ThreadPoolExecutor(
CORE_POOL_SIZE
,CORE_MAX_POOL_SIZE
,KEEP_ALIVE_TIME
,KEEP_ALIVE_TIME_UNIT
,taskQueue
);
return ret;
}
private Handler initHandler() {
Handler ret = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
for (Map.Entry<String, Model.Base> entry : observers.entrySet()) {
entry.getValue().onEvent(msg);
}
}
};
return ret;
}
public void executeCommand(Message command) {
SetTask setTask;
ItemTask itemTask;
ImageProviderTask imageProviderTask;
if (command != null) {
switch (command.what) {
case Command.SET_GET_ALL :
setTask = new SetTask(Command.SET_GET_ALL,
Process.THREAD_PRIORITY_MORE_FAVORABLE);
threadPool.execute(setTask);
break;
case Command.SET_REORDER :
setTask = new SetTask(Command.SET_REORDER,
Process.THREAD_PRIORITY_BACKGROUND);
setTask.setsToUpdate = (List<Set>) command.obj;
threadPool.execute(setTask);
break;
case Command.SET_GET_ITEMS :
setTask = new SetTask(Command.SET_GET_ITEMS,
Process.THREAD_PRIORITY_MORE_FAVORABLE);
setTask.setId = command.arg1;
threadPool.execute(setTask);
break;
case Command.SET_GET_PACKED_ITEMS :
setTask = new SetTask(Command.SET_GET_PACKED_ITEMS,
Process.THREAD_PRIORITY_MORE_FAVORABLE);
setTask.setId = command.arg1;
threadPool.execute(setTask);
break;
case Command.SET_UNPACK_ITEMS :
setTask = new SetTask(Command.SET_UNPACK_ITEMS,
Process.THREAD_PRIORITY_DEFAULT);
setTask.setId = command.arg1;
threadPool.execute(setTask);
case Command.ITEM_GET_CATEGORIES :
itemTask = new ItemTask(Command.ITEM_GET_CATEGORIES,
Process.THREAD_PRIORITY_MORE_FAVORABLE);
threadPool.execute(itemTask);
break;
case Command.ITEM_INSERT :
itemTask = new ItemTask(Command.ITEM_INSERT,
Process.THREAD_PRIORITY_BACKGROUND);
itemTask.item = (Item) command.obj;
itemTask.setId = command.arg1;
threadPool.execute(itemTask);
break;
case Command.ITEM_DELETE_FROM_SET :
itemTask = new ItemTask(Command.ITEM_DELETE_FROM_SET,
Process.THREAD_PRIORITY_BACKGROUND);
itemTask.setId = command.arg1;
itemTask.itemId = command.arg2;
threadPool.execute(itemTask);
break;
case Command.ITEM_PACK :
itemTask = new ItemTask(Command.ITEM_PACK,
Process.THREAD_PRIORITY_BACKGROUND);
itemTask.setId = command.arg1;
itemTask.itemId = command.arg2;
threadPool.execute(itemTask);
break;
case Command.ITEM_UNPACK :
itemTask = new ItemTask(Command.ITEM_UNPACK,
Process.THREAD_PRIORITY_BACKGROUND);
itemTask.setId = command.arg1;
itemTask.itemId = command.arg2;
threadPool.execute(itemTask);
break;
case Command.ITEM_GET_IMAGE :
Item item = findItem(command.arg1);
if (item != null) {
imageProviderTask = new ImageProviderTask(Command.ITEM_GET_IMAGE,
Process.THREAD_PRIORITY_DEFAULT);
imageProviderTask.item = item;
threadPool.execute(imageProviderTask);
}
break;
case Command.MY_LIST_ITEM_ADD :
break;
case Command.MY_LIST_ITEM_DELETE :
break;
case Command.MY_LIST_POST :
break;
case Command.MY_LIST_CLEAR :
break;
case Command.SYNC :
threadPool.execute(new SyncTask(Command.SYNC,
Process.THREAD_PRIORITY_BACKGROUND));
break;
case Command.SYNC_IF_NOT_EXISTS :
threadPool.execute(new SyncTask(Command.SYNC_IF_NOT_EXISTS,
Process.THREAD_PRIORITY_MORE_FAVORABLE));
break;
}
}
}
/////////////////////// DATABASE /////////////////////
//region Database
private SQLiteDatabase getReadDB(){
return helper.getReadableDatabase();
}
private SQLiteDatabase getWriteDB(){
return helper.getWritableDatabase();
}
// inserts
private void insertTimestamp(Timestamp timestamp) {
if (timestamp != null && timestamp.timestamp > 0) {
ContentValues values;
SQLiteDatabase db = getWriteDB();
try {
db.beginTransaction();
values = Db.LogTable.toContentValues(timestamp);
db.insert(Db.LogTable.TABLE_NAME, null, values);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
db.close();
}
}
}
private void insertItems(List<Item> items) {
if (items != null && !items.isEmpty()) {
ContentValues values;
SQLiteDatabase db = getWriteDB();
try {
db.beginTransaction();
for (Item item : items) {
values = Db.ItemsTable.toContentValues(item);
db.insert(Db.ItemsTable.TABLE_NAME, null, values);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
db.close();
}
}
}
private void insertCategories(List<Category> categories) {
if (categories != null && !categories.isEmpty()) {
ContentValues values;
SQLiteDatabase db = getWriteDB();
try {
db.beginTransaction();
for (Category category : categories) {
values = Db.CategoriesTable.toContentValues(category);
db.insert(Db.CategoriesTable.TABLE_NAME, null, values);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
db.close();
}
}
}
private void insertSets(List<Set> sets) {
if (sets != null && !sets.isEmpty()) {
ContentValues values;
int i = 0;
SQLiteDatabase db = getWriteDB();
try {
db.beginTransaction();
for (Set set : sets) {
values = Db.SetsTable.toContentValues(set, i);
db.insert(Db.SetsTable.TABLE_NAME, null, values);
insertSetItems(set, db);
++i;
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
db.close();
}
}
}
private void insertSetItems(Set set, SQLiteDatabase db) {
if (set != null && db != null) {
if (!set.getItems().isEmpty()) {
ContentValues values;
int setId = set.getId();
try {
db.beginTransaction();
for (Integer itemid : set.getItems()) {
values = Db.SetItemsTable.toContentValues(setId, itemid);
db.insert(Db.SetItemsTable.TABLE_NAME, null, values);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
}
}
private void insertSetItem(int setId, int itemId) {
ContentValues values;
SQLiteDatabase db = getWriteDB();
try {
db.beginTransaction();
values = Db.SetItemsTable.toContentValues(setId, itemId);
db.insert(Db.SetItemsTable.TABLE_NAME, null, values);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
db.close();
}
}
// reads
private boolean LogExist() {
boolean ret;
SQLiteDatabase db = getReadDB();
Cursor cursor = db.query(Db.LogTable.TABLE_NAME,
new String[] {Db.LogTable.COLUMN_ID}, null, null, null, null, null, "1");
ret = cursor.moveToNext();
cursor.close();
db.close();
return ret;
}
private Item findItem(int id) {
Item ret = null;
Cursor cursor = null;
SQLiteDatabase db = null;
try {
db = getReadDB();
String query = String.format("SELECT * FROM %s a WHERE a.%s = %d LIMIT 1",
Db.ItemsTable.TABLE_NAME, Db.ItemsTable.COLUMN_ID, id);
cursor = db.rawQuery(query, null);
if (cursor.moveToNext()) {
ret = Db.ItemsTable.parseCursor(cursor);
}
} catch (Exception e) {
//TODO write to log here
} finally {
if (cursor != null)
cursor.close();
if (db != null)
db.close();
}
return ret;
}
private List<Item> readItems(int setId, boolean packed) {
List<Item> ret = new ArrayList<>(256);
Cursor cursor = null;
SQLiteDatabase db = null;
Item item;
String query = String.format(
"SELECT a.%s, a.%s, a.%s, a.%s, a.%s, a.%s, a.%s, a.%s, a.%s FROM %s a INNER JOIN %s b ON a.%s = b.%s WHERE b.%s = ? AND b.%s <> 1 AND b.%s %s 1",
Db.ItemsTable.COLUMN_ID,
Db.ItemsTable.COLUMN_NAME,
Db.ItemsTable.COLUMN_CATEGORY,
Db.ItemsTable.COLUMN_DESCRIPTION,
Db.ItemsTable.COLUMN_BUY_URLS,
Db.ItemsTable.COLUMN_PHOTO_URL,
Db.ItemsTable.COLUMN_PHOTO_THUMB_URL,
Db.ItemsTable.COLUMN_PHOTO_LOCAL,
Db.ItemsTable.COLUMN_PHOTO_THUMB_LOCAL,
Db.ItemsTable.TABLE_NAME,
Db.SetItemsTable.TABLE_NAME,
Db.ItemsTable.COLUMN_ID,
Db.SetItemsTable.COLUMN_ITEM,
Db.SetItemsTable.COLUMN_SET,
Db.SetItemsTable.COLUMN_DELETED,
Db.SetItemsTable.COLUMN_PACKED,
packed ? "=" : "<>");
try {
db = getReadDB();
cursor = db.rawQuery(query, new String[]{String.valueOf(setId)});
while (cursor.moveToNext()) {
item = Db.ItemsTable.parseCursor(cursor);
ret.add(item);
}
} catch (SQLiteException e) {
//TODO write to log here
} catch (Exception e) {
//TODO write to log here
} finally {
if (cursor != null)
cursor.close();
if (db != null)
db.close();
}
return ret;
}
private Hashtable<Integer, Category> readCategories() {
Hashtable<Integer, Category> ret = new Hashtable<>(20, 0.9f);
Cursor cursor = null;
SQLiteDatabase db = null;
Category category;
try {
db = getReadDB();
cursor = db.query(Db.CategoriesTable.TABLE_NAME,
new String[]{Db.CategoriesTable.COLUMN_ID,
Db.CategoriesTable.COLUMN_NAME},
null,null,null,null,null);
while (cursor.moveToNext()) {
category = Db.CategoriesTable.parseCursor(cursor);
ret.put(category.getId(), category);
}
} catch (SQLiteException e) {
//TODO write to log here
} catch (Exception e) {
//TODO write to log here
} finally {
if (cursor != null)
cursor.close();
if (db != null)
db.close();
}
return ret;
}
private Set readSet(SQLiteDatabase db, int setId) {
Set ret = null;
Cursor cursor;
String query = String.format("SELECT * FROM %s a WHERE a.%s = %d LIMIT 1",
Db.SetsTable.TABLE_NAME, Db.SetsTable.COLUMN_ID, setId);
cursor = db.rawQuery(query, null);
if (cursor.moveToNext())
ret = Db.SetsTable.parseCursor(cursor);
if (cursor != null)
cursor.close();
return ret;
}
private List<Set> readSets() {
List<Set> ret = new ArrayList<>(12);
Cursor cursor = null;
SQLiteDatabase db = null;
Set set;
try {
db = getReadDB();
String query = String.format("SELECT * FROM %s", Db.SetsTable.TABLE_NAME);
cursor = db.rawQuery(query, null);
while (cursor.moveToNext()) {
set = Db.SetsTable.parseCursor(cursor);
ret.add(set);
}
Collections.sort(ret);
} catch (SQLiteException e) {
//TODO write to log here
} catch (Exception e) {
//TODO write to log here
} finally {
if (cursor != null)
cursor.close();
if (db != null)
db.close();
}
return ret;
}
// updates
private int updateItemLocalPic(int id, String path) {
int ret = 0;
SQLiteDatabase db = null;
ContentValues values;
try {
db = getWriteDB();
db.beginTransaction();
values = new ContentValues();
values.put(Db.ItemsTable.COLUMN_PHOTO_LOCAL, path);
ret = db.update(Db.ItemsTable.TABLE_NAME, values, "_id = ?",
new String[]{String.valueOf(id)});
db.setTransactionSuccessful();
} catch (SQLiteException e) {
//TODO write to log here
} catch (Exception e) {
//TODO write to log here
} finally {
if (db != null) {
db.endTransaction();
db.close();
}
}
return ret;
}
private int updateSetsOrder(List<Set> reorderedSet) {
int ret = 0;
SQLiteDatabase db = null;
ContentValues values;
try {
db = getWriteDB();
db.beginTransaction();
for (Set set : reorderedSet) {
values = new ContentValues();
values.put(Db.SetsTable.COLUMN_LINE_NUMBER, set.getLineNumber());
ret += db.update(Db.SetsTable.TABLE_NAME, values, "_id = ?",
new String[]{String.valueOf(set.getId())});
}
db.setTransactionSuccessful();
} catch (SQLiteException e) {
//TODO write to log here
} catch (Exception e) {
//TODO write to log here
} finally {
if (db != null) {
db.endTransaction();
db.close();
}
}
return ret;
}
private int updateSetItemDeleted(int setId, int itemId, boolean del) {
int ret = 0;
SQLiteDatabase db = null;
ContentValues values;
try {
db = getWriteDB();
db.beginTransaction();
values = new ContentValues();
values.put(Db.SetItemsTable.COLUMN_DELETED, del);
ret = db.update(Db.SetItemsTable.TABLE_NAME, values, String.format("%s = ? AND %s = ?",
Db.SetItemsTable.COLUMN_SET, Db.SetItemsTable.COLUMN_ITEM ),
new String[]{String.valueOf(setId), String.valueOf(itemId)});
db.setTransactionSuccessful();
} catch (SQLiteException e) {
//TODO write to log here
} catch (Exception e) {
//TODO write to log here
} finally {
if (db != null) {
db.endTransaction();
db.close();
}
}
return ret;
}
private int updateSetItemsPacked(int setId, boolean pack) {
int ret = 0;
SQLiteDatabase db = null;
ContentValues values;
Set set;
try {
db = getWriteDB();
db.beginTransaction();
/*
String query = String.format("UPDATE %s SET %s = %d where %s = %d",
Db.SetItemsTable.TABLE_NAME,
Db.SetItemsTable.COLUMN_PACKED,
pack,
Db.SetItemsTable.COLUMN_SET,
setId);
Cursor cursor = db.rawQuery(query, null);*/
values = new ContentValues();
values.put(Db.SetItemsTable.COLUMN_PACKED, pack);
ret = db.update(Db.SetItemsTable.TABLE_NAME, values, String.format("%s = ?",
Db.SetItemsTable.COLUMN_SET),
new String[]{String.valueOf(setId)});
set = readSet(db, setId);
if (set != null) {
values = new ContentValues();
values.put(Db.SetsTable.COLUMN_PACKED_QTY, pack ? set.getActiveQty() : 0);
ret += db.update(Db.SetsTable.TABLE_NAME, values, String.format("%s = ?",
Db.SetsTable.COLUMN_ID),
new String[]{String.valueOf(setId)});
}
db.setTransactionSuccessful();
} catch (SQLiteException e) {
//TODO write to log here
} catch (Exception e) {
//TODO write to log here
} finally {
if (db != null) {
db.endTransaction();
db.close();
}
}
return ret;
}
private int updateSetItemPacked(int setId, int itemId, boolean pack) {
int ret = 0;
SQLiteDatabase db = null;
ContentValues values;
Set set;
try {
db = getWriteDB();
db.beginTransaction();
values = new ContentValues();
values.put(Db.SetItemsTable.COLUMN_PACKED, pack);
ret = db.update(Db.SetItemsTable.TABLE_NAME, values, String.format("%s = ? AND %s = ?",
Db.SetItemsTable.COLUMN_SET, Db.SetItemsTable.COLUMN_ITEM ),
new String[]{String.valueOf(setId), String.valueOf(itemId)});
set = readSet(db, setId);
if (set != null) {
values = new ContentValues();
values.put(Db.SetsTable.COLUMN_PACKED_QTY, pack ? set.getPackedQty() + 1 : set.getPackedQty() - 1);
ret += db.update(Db.SetsTable.TABLE_NAME, values, String.format("%s = ?",
Db.SetsTable.COLUMN_ID),
new String[]{String.valueOf(setId)});
}
db.setTransactionSuccessful();
} catch (SQLiteException e) {
//TODO write to log here
} catch (Exception e) {
//TODO write to log here
} finally {
if (db != null) {
db.endTransaction();
db.close();
}
}
return ret;
}
//endregion
/////////////////////// TASK CLASSES //////////////////
//region Task classes
// MY LIST CLASS
private class MyListTask implements Runnable {
int currentCommand;
int priority;
public MyListTask(int command, int priority) {
this.currentCommand = command;
this.priority = priority;
}
@Override
public void run() {
android.os.Process.setThreadPriority(priority);
Message message = Message.obtain();
switch (currentCommand) {
}
handler.sendMessage(message);
}
}
// ITEM CLASS
private class ItemTask implements Runnable {
int currentCommand;
int priority;
int setId;
int itemId;
Item item;
public ItemTask(int command, int priority) {
this.currentCommand = command;
this.setId = -1;
this.itemId = -1;
this.priority = priority;
}
@Override
public void run() {
android.os.Process.setThreadPriority(priority);
Message message = Message.obtain();
switch (currentCommand) {
case Command.ITEM_DELETE_FROM_SET :
message.arg1 = updateSetItemDeleted(setId, itemId, true);
if (message.arg1 > 0)
message.what = Event.ITEM_FROM_SET_DELETED;
else
message.what = Event.ITEM_FROM_SET_ERROR;
break;
case Command.ITEM_INSERT :
List<Item> items = new ArrayList<>();
items.add(item);
if (items.isEmpty())
message.what = Event.ITEM_INSERT_ERROR;
else {
insertItems(items);
insertSetItem(setId, item.getId());
message.what = Event.ITEM_INSERTED;
message.arg1 = setId;
message.arg2 = item.getId();
}
break;
case Command.ITEM_PACK :
message.arg1 = updateSetItemPacked(setId, itemId, true);
if (message.arg1 > 0)
message.what = Event.ITEM_PACKED;
else
message.what = Event.ITEM_PACK_ERROR;
break;
case Command.ITEM_UNPACK :
message.arg1 = updateSetItemPacked(setId, itemId, false);
if (message.arg1 > 0)
message.what = Event.ITEM_UNPACKED;
else
message.what = Event.ITEM_UNPACK_ERROR;
break;
case Command.ITEM_GET_CATEGORIES :
Hashtable<Integer, Category> res = readCategories();
if (res.isEmpty())
message.what = Event.ITEM_CATEGORY_LOAD_ERROR;
else {
message.what = Event.ITEM_CATEGORY_LOAD_COMPLETED;
message.obj = res;
}
break;
}
handler.sendMessage(message);
}
}
// SET CLASS
private class SetTask implements Runnable {
int currentCommand;
int priority;
int setId;
List<Set> setsToUpdate;
List<Item> items;
public SetTask(int command, int priority) {
this.currentCommand = command;
this.setId = -1;
this.setsToUpdate = new ArrayList<>();
this.priority = priority;
}
@Override
public void run() {
android.os.Process.setThreadPriority(priority);
Message message = Message.obtain();
switch (currentCommand) {
case Command.SET_GET_ALL :
List<Set> sets = readSets();
if (sets.isEmpty())
message.what = Event.SET_LOAD_ERROR;
else {
message.what = Event.SET_LOAD_COMPLETED;
message.obj = sets;
}
break;
case Command.SET_GET_ITEMS :
items = readItems(setId, false);
if (items.isEmpty())
message.what = Event.SET_ITEMS_LOAD_ERROR;
else {
Collections.sort(items);
message.what = Event.SET_ITEMS_LOAD_COMPLETED;
message.obj = items;
message.arg1 = setId;
}
break;
case Command.SET_REORDER :
message.arg1 = updateSetsOrder(setsToUpdate);
if (message.arg1 > 0)
message.what = Event.SET_REORDER_COMPLETED;
else
message.what = Event.SET_REORDER_ERROR;
break;
case Command.SET_GET_PACKED_ITEMS :
items = readItems(setId, true);
if (items.isEmpty())
message.what = Event.SET_PACKED_LOAD_ERROR;
else {
Collections.sort(items);
message.what = Event.SET_PACKED_LOAD_COMPLETED;
message.obj = items;
message.arg1 = setId;
}
break;
case Command.SET_UNPACK_ITEMS :
message.arg1 = updateSetItemsPacked(setId, false);
message.arg2 = setId;
if (message.arg1 > 0)
message.what = Event.SET_UNPACK_COMPLETED;
else
message.what = Event.SET_UNPACK_ERROR;
break;
}
handler.sendMessage(message);
}
}
// SYNC CLASS
private class SyncTask implements Runnable {
int currentCommand;
int priority;
int statusCode;
public SyncTask(int command, int priority) {
this.currentCommand = command;
this.priority = priority;
}
@Override
public void run() {
android.os.Process.setThreadPriority(priority);
Message message = Message.obtain();
switch (currentCommand) {
case Command.SYNC:
try {
Call<List<Set>> call = api.getSets();
call.enqueue(new Callback<List<Set>>() {
@Override
public void onResponse(Call<List<hikapro.com.backpack.model.entities.Set>> call, Response<List<Set>> response) {
statusCode = response.code();
// TODO
// check if first time
// if not check for updates else
// insert into database here
insertSets(response.body());
}
@Override
public void onFailure(Call<List<hikapro.com.backpack.model.entities.Set>> call, Throwable t) {
}
});
message.what = Event.SYNC_COMPLETED;
} catch (Exception e) {
message.what = Event.SYNC_FAILED;
}
finally {
message.arg1 = statusCode;
handler.sendMessage(message);
}
break;
case Command.SYNC_IF_NOT_EXISTS:
if (LogExist()) {
message.what = Event.SYNC_COMPLETED;
} else {
try {
Response<List<Set>> response0 = api.getSets().execute();
insertSets(response0.body());
statusCode = response0.code();
Response<List<Category>> response1 = api.getItemCategories().execute();
insertCategories(response1.body());
statusCode = response1.code();
Response<List<Item>> response2 = api.getItems().execute();
insertItems(response2.body());
statusCode = response2.code();
Response<Timestamp> response3 = api.getTimestamp().execute();
insertTimestamp(response3.body());
statusCode = response3.code();
message.what = Event.SYNC_COMPLETED;
} catch (IOException e ){
message.what = Event.SYNC_FAILED;
} finally {
message.arg1 = statusCode;
handler.sendMessage(message);
}
}
break;
}
}
}
// IMAGE PROVIDER CLASS
private class ImageProviderTask implements Runnable {
int currentCommand;
int priority;
Item item;
public ImageProviderTask(int command, int priority) {
this.currentCommand = command;
this.priority = priority;
}
@Override
public void run() {
android.os.Process.setThreadPriority(priority);
Message message = Message.obtain();
switch (currentCommand) {
case Command.ITEM_GET_IMAGE :
try {
Bitmap bitmap = loadItemImage(item);
if (bitmap != null) {
message.what = Event.ITEM_IMAGE_LOAD_COMPLETED;
message.obj = bitmap;
}
else
message.what = Event.ITEM_IMAGE_LOAD_ERROR;
} catch (Exception e) {
message.what = Event.ITEM_IMAGE_LOAD_ERROR;
}
break;
}
handler.sendMessage(message);
}
}
//endregion
private Bitmap loadItemImage(Item item){
ImageDownloadHelper downloadHelper = new ImageDownloadHelper();
Bitmap bitmap = null;
String filename = null;
if (item != null) {
bitmap = BitmapFactory.decodeFile(item.getPhotoLocal());
// cannot retrieve, download and save then
if (bitmap == null) { // return it
bitmap = downloadHelper.loadImage(item.getPhotoUrl());
if (bitmap != null) {
if (downloadHelper.isExternalStorageWritable()) {
filename = downloadHelper.saveImageExternal(
downloadHelper.generateFileName(item.getPhotoUrl()), bitmap);
} else {
filename = downloadHelper.saveImageInternal(
downloadHelper.generateFileName(item.getPhotoUrl()), bitmap);
}
updateItemLocalPic(item.getId(), filename);
}
}
}
return bitmap;
}
}

View File

@ -1,129 +0,0 @@
package hikapro.com.backpack.presenter;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
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.ViewGroup;
import android.widget.Toast;
import java.lang.ref.WeakReference;
import hikapro.com.backpack.R;
import hikapro.com.backpack.model.Model;
import hikapro.com.backpack.model.entities.Item;
import hikapro.com.backpack.presenter.adapters.ItemDetailAdapter;
import hikapro.com.backpack.view.View;
import hikapro.com.backpack.view.recycler.DetailViewHolder;
/**
* Created by tariel on 23/04/16.
*/
public class ItemDetailPresenter implements Presenter.ItemDetail {
private WeakReference<View.ItemDetail> view;
private Model.Detail model;
private ItemDetailAdapter adapter;
private Item item;
public ItemDetailPresenter() {
this.adapter = new ItemDetailAdapter(this);
}
// life cycle -->
@Override
public void onDestroy(boolean isChangingConfiguration) {
view = null;
model.onDestroy(isChangingConfiguration);
if ( !isChangingConfiguration ) {
model = null;
}
}
@Override
public android.view.View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
android.view.View view = inflater.inflate(R.layout.fragment_item_detail, container, false);
LinearLayoutManager llm = new LinearLayoutManager(getActivityContext());
RecyclerView detailRecycler = (RecyclerView) view.findViewById(R.id.item_detail_recycler);
detailRecycler.setLayoutManager(llm);
detailRecycler.setAdapter(adapter);
detailRecycler.setItemAnimator(new DefaultItemAnimator());
model.executeQuery();
return view;
}
@Override
public void onSaveInstanceState(Bundle outState) {
}
// life cycle <--
// process -->
@Override
public void notifyDataSetChanged() {
adapter.notifyDataSetChanged();
}
// process <--
// other impl -->
@Override
public void setView(View.ItemDetail view) {
this.view = new WeakReference<>(view);
this.item = getView().getItem();
}
@Override
public void setModel(Model.Detail model) {
this.model = model;
}
@Override
public Model.Detail getModel() {
return model;
}
@Override
public Item getCurrentItem() {
return item;
}
@Override
public Context getAppContext() {
try {
return getView().getAppContext();
} catch (NullPointerException e) {
return null;
}
}
@Override
public Context getActivityContext() {
try {
return getView().getActivityContext();
} catch (NullPointerException e) {
return null;
}
}
@Override
public void showMessage(String message) {
Toast.makeText(getView().getAppContext(), message, Toast.LENGTH_SHORT).show();
}
@Override
public void displayPicture(Bitmap bitmap) {
}
// other impl <--
private View.ItemDetail getView() throws NullPointerException {
if ( view != null )
return view.get();
else
throw new NullPointerException("View is unavailable");
}
}

View File

@ -1,55 +0,0 @@
package hikapro.com.backpack.presenter.adapters;
import android.graphics.Bitmap;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import hikapro.com.backpack.R;
import hikapro.com.backpack.model.Model;
import hikapro.com.backpack.presenter.Presenter;
import hikapro.com.backpack.view.recycler.DetailViewHolder;
/**
* Created by tariel on 23/04/16.
*/
public class ItemDetailAdapter extends RecyclerView.Adapter<DetailViewHolder> {
private Presenter.ItemDetail presenter;
public ItemDetailAdapter(Presenter.ItemDetail presenter) {
this.presenter = presenter;
}
@Override
public int getItemCount() {
return presenter.getModel().getCount();
}
@Override
public void onBindViewHolder(DetailViewHolder holder, int position) {
hikapro.com.backpack.model.entities.Item item = presenter.getModel().findItem(position);
holder.title.setText(item.getName());
holder.description.setText(item.getDescription());
Bitmap bitmap = presenter.getModel().getPicture();
if (bitmap != null)
holder.photo.setImageBitmap(bitmap);
holder.title.setOnClickListener(new android.view.View.OnClickListener() {
@Override
public void onClick(android.view.View view) {
presenter.showMessage("On detail click");
}
});
}
@Override
public DetailViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
DetailViewHolder viewHolder;
android.view.View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_detail,
parent, false);
viewHolder = new DetailViewHolder(v);
return viewHolder;
}
}

View File

@ -1,216 +0,0 @@
package hikapro.com.backpack.presenter.adapters;
import android.graphics.Color;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.HashMap;
import hikapro.com.backpack.R;
import hikapro.com.backpack.model.entities.Category;
import hikapro.com.backpack.model.entities.Item;
import hikapro.com.backpack.presenter.Presenter;
import hikapro.com.backpack.presenter.adapters.helper.items.StickyHeaderAdapter;
import hikapro.com.backpack.view.recycler.HeaderViewHolder;
import hikapro.com.backpack.view.recycler.ItemViewHolder;
/**
* Created by tariel on 01/05/16.
*/
public class ItemListAdapter extends RecyclerView.Adapter<ItemViewHolder> implements StickyHeaderAdapter<HeaderViewHolder> {
private static final int PENDING_REMOVAL_TIMEOUT = 4000; // 4sec
boolean undoOn; // is undo on, you can turn it on from the toolbar menu
private Handler handler = new Handler(); // hanlder for running delayed runnables
HashMap<Item, Runnable> pendingRunables = new HashMap<>(); // map of items to pending runnables, so we can cancel a removal if need be
private Presenter.ItemList presenter;
private boolean checkAll;
public ItemListAdapter(Presenter.ItemList presenter) {
this.presenter = presenter;
}
@Override
public int getItemCount() {
int res = presenter.getModel().getItemsCount();
return res;
}
@Override
public long getItemId(int position) {
long ret = presenter.getModel().getItemId(position);
return ret;
}
@Override
public void onBindViewHolder(final ItemViewHolder holder, final int position) {
final Item item = presenter.getModel().getItemByPosition(position);
if (presenter.getModel().isPendingRemoval(item)) {
// we need to show the "undo" state of the row
holder.itemView.setBackgroundColor(Color.RED);
holder.checkBox.setVisibility(View.GONE);
holder.undoButton.setVisibility(View.VISIBLE);
holder.undoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// user wants to undo the removal, let's cancel the pending task
Runnable pendingRemovalRunnable = pendingRunables.get(item);
pendingRunables.remove(item);
if (pendingRemovalRunnable != null) handler.removeCallbacks(pendingRemovalRunnable);
presenter.getModel().pendingRemoveCancel(item);
// this will rebind the row in "normal" state
notifyItemChanged(position);
}
});
} else {
holder.checkBox.setVisibility(View.VISIBLE);
holder.checkBox.setChecked(checkAll);
holder.checkBox.setText(item.getName() + " " + item.getId() + " pos " + position);//TODO del
holder.id = item.getId();
holder.checkBox.setOnClickListener(new android.view.View.OnClickListener() {
@Override
public void onClick(View v) {
if (holder.checkBox.isChecked()) {
pack(holder.id, position);
// presenter.packItem(); TODO wtf
} else {
unpack(holder.id, position);
// presenter.unpackItem(); TODO wtf
}
}
});
holder.infoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
presenter.showDetails(holder.id);
}
});
holder.itemView.setBackgroundColor(0x33FF99);
holder.undoButton.setVisibility(View.GONE);
holder.undoButton.setOnClickListener(null);
}
}
@Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
ItemViewHolder viewHolder;
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_item,
parent, false);
viewHolder = new ItemViewHolder(v);
return viewHolder;
}
public void setUndoOn(boolean undoOn) {
this.undoOn = undoOn;
}
public boolean isUndoOn() {
return undoOn;
}
public void add(Item item) {
presenter.getModel().insertItem(item);
notifyDataSetChanged();
}
public void clear() {
presenter.getModel().clear();
notifyDataSetChanged();
}
public void filter(String query) {
presenter.getModel().filter(query);
notifyDataSetChanged();
}
@Override
public long getHeaderId(int position) {
/*if (position == 0) {
return -1;
} else {*/
return presenter.getModel().getHeaderId(position);
//}
}
@Override
public HeaderViewHolder onCreateHeaderViewHolder(ViewGroup parent) {
HeaderViewHolder viewHolder;
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.view_header, parent, false);
viewHolder = new HeaderViewHolder(v);
return viewHolder;
}
@Override
public void onBindHeaderViewHolder(HeaderViewHolder holder, int position) {
Category category = presenter.getModel().getCategoryByPosition(position);
holder.id = category.getId();
holder.title.setText(category.getName());
holder.title.setBackgroundColor(0x2B1E15);
}
public void pendingRemoval(final int position) {
final Item item = presenter.getModel().getItemByPosition(position);
if (! presenter.getModel().isPendingRemoval(item)) {
presenter.getModel().pendingRemove(item);
// this will redraw row in "undo" state
notifyItemChanged(position);
// let's create, store and post a runnable to remove the item
Runnable pendingRemovalRunnable = new Runnable() {
@Override
public void run() {
remove(item, position);
}
};
handler.postDelayed(pendingRemovalRunnable, PENDING_REMOVAL_TIMEOUT);
pendingRunables.put(item, pendingRemovalRunnable);
}
}
public void remove(Item item, int position) {
presenter.getModel().deleteItem(item);
notifyItemRemoved(position);
}
public void remove(int position) {
Item item = presenter.getModel().getItemByPosition(position);
presenter.getModel().deleteItem(item);
notifyItemRemoved(position);
}
public boolean isPendingRemoval(int position) {
Item item = presenter.getModel().getItemByPosition(position);
return presenter.getModel().isPendingRemoval(item);
}
public void pack(int itemId, int position) {
presenter.getModel().packItem(itemId);
notifyDataSetChanged();
/*
notifyItemRemoved(position);
notifyItemRangeRemoved(position, getItemCount());
*/
}
public void unpack(int itemId, int position) {
presenter.getModel().unpackItem(itemId);
//notifyItemRemoved(position);
notifyDataSetChanged();
}
public void unpackAll() {
}
public void setCheckAll(boolean checkAll) {
this.checkAll = checkAll;
}
}

View File

@ -1,14 +0,0 @@
package hikapro.com.backpack.presenter.adapters;
import hikapro.com.backpack.presenter.Presenter;
import hikapro.com.backpack.presenter.adapters.ItemListAdapter;
/**
* Created by tariel on 12/05/16.
*/
public class PackedListAdapter extends ItemListAdapter {
public PackedListAdapter(Presenter.ItemList presenter) {
super(presenter);
}
}

View File

@ -1,29 +0,0 @@
package hikapro.com.backpack.view.recycler;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import hikapro.com.backpack.R;
/**
* Created by tariel on 23/04/16.
*/
public class DetailViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public TextView description;
public ImageView photo;
public DetailViewHolder(View v) {
super(v);
setupViews(v);
}
private void setupViews(View view) {
title = (TextView) view.findViewById(R.id.item_title);
description = (TextView) view.findViewById(R.id.item_description);
photo = (ImageView) view.findViewById(R.id.item_photo);
}
}

View File

@ -1,34 +0,0 @@
package hikapro.com.backpack.view.recycler;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.TextView;
import hikapro.com.backpack.R;
/**
* Created by tariel on 01/05/16.
*/
public class ItemViewHolder extends RecyclerView.ViewHolder {
public int id;
public CheckBox checkBox;
public Button undoButton;
public ImageButton infoButton;
public ItemViewHolder(View v) {
super(v);
setupViews(v);
}
private void setupViews(View view) {
infoButton = (ImageButton) view.findViewById(R.id.info_button);
checkBox = (CheckBox) view.findViewById(R.id.item_checkbox);
undoButton = (Button) view.findViewById(R.id.undo_button);
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 160 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 260 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 579 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 119 B

Some files were not shown because too many files have changed in this diff Show More