Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.github.kubatatami.judonetworking.observers;
  
  import  android.annotation.TargetApi;
  import  android.app.Activity;
  import  android.content.Context;
  import  android.database.DataSetObserver;
  import  android.os.Build;
  import  android.support.v4.app.FragmentActivity;
  import  android.util.Pair;
 import  android.view.View;
 import  android.view.ViewGroup;
 import  android.widget.Adapter;
 import  android.widget.ListView;
 import  android.widget.TextView;
 
 
 import java.util.List;
 import java.util.Map;
Created with IntelliJ IDEA. User: jbogacki Date: 08.04.2013 Time: 22:23
 
 public class ObserverHelper {
     private List<Pair<Adapter, DataSetObserver>> dataAdapters = new ArrayList<Pair<Adapter, DataSetObserver>>();
     private Map<View, Pair<ObservableWrapperWrapObserver>> viewObservers = new HashMap<View, Pair<ObservableWrapperWrapObserver>>();
 
     private static final String splitter = "\\.";
     private static final Pattern pattern = Pattern.compile("\\[[^\\]]*\\]");
     static final String convention = "Changed";
     private Context context;
 
     private static ErrorLogger errorLogger;
 
     private static Object dataObject;
     static Class<?> dataClass;
 
     public static void setDataObject(Object data) {
          = data;
          = data.getClass();
     }
 
     public static void setDataClass(Class<?> dataClass) {
          = null;
         . = dataClass;
     }
 
     public ObserverHelper(Context context) {
         this. = context;
     }
 
     public static void setErrorLogger(ErrorLogger errorLogger) {
         . = errorLogger;
     }
 
     public void start(final android.support.v4.app.Fragment fragment, View view) {
         startInternal(fragmentview);
     }
 
     public void start(final android.app.Fragment fragment, View view) {
         startInternal(fragmentview);
     }
 
     public void start(final Activity activity, View view) {
         startInternal(activityview);
     }
 
     public void start(final FragmentActivity activity, View view) {
         startInternal(activityview);
     }
 
     protected ObserverSettings getSettingsAnnotation(Class<?> clazz) {
         for (; clazz != nullclazz = clazz.getSuperclass()) {
             ObserverSettings settings = clazz.getAnnotation(ObserverSettings.class);
             if (settings != null) {
                 return settings;
             }
         }
         return null;
     }
 
     @SuppressWarnings("unchecked")
     protected void startInternal(final Object object, View view) {
         ObserverSettings settings = getSettingsAnnotation(object.getClass());
         if (settings != null) {
             .clear();
             .clear();
             .clear();
             if (settings.dataObservers() && . != null) {
                findDataObserver(object);
            }
            if (settings.tags() && view != null) {
                findViewObserver(viewobject);
            }
        }
    }
    private void findViewObserver(View viewObject object) {
        if (view instanceof ViewGroup && !(view instanceof ListView) && !isFromFragment(viewobject)) {
            ViewGroup group = (ViewGroup) view;
            for (int i = 0; i < group.getChildCount(); i++) {
                View viewElem = group.getChildAt(i);
                findViewObserver(viewElemobject);
            }
        } else {
            linkViewObserver(viewobject);
        }
    }
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private boolean isFromFragment(View viewObject object) {
        if (view.getId() == -1) {
            return false;
        }
        if (object instanceof FragmentActivity) {
            return ((FragmentActivity) object).getSupportFragmentManager().findFragmentById(view.getId()) != null;
        } else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB && object instanceof Activity) {
            return ((Activity) object).getFragmentManager().findFragmentById(view.getId()) != null;
        } else {
            return false;
        }
    }
    @SuppressWarnings("unchecked")
    private void linkViewObserver(final View viewfinal Object object) {
        try {
            if (view.getTag() != null && view.getTag() instanceof String) {
                final String tag = (Stringview.getTag();
                final List<ObservableWrapperresults = findObservablesByTag(tag);
                WrapObserver observer = new WrapObserver() {
                    @Override
                    public void update(Object data) {
                        try {
                            if (view instanceof TextView) {
                                TextView textView = (TextView) view;
                                String result = buildResult(tag.substring(1, tag.length() - 1), object);
                                textView.setText(result);
                            }
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }
                };
                if (results.size() > 0) {
                    for (ObservableWrapper result : results) {
                        result.addObserver(observer);
                        .put(viewnew Pair<ObservableWrapperWrapObserver>(resultobserver));
                    }
                } else if (view instanceof TextView && tag.matches("\\[.*\\]")) {
                    TextView textView = (TextView) view;
                    String result = buildResult(tag.substring(1, tag.length() - 1), object);
                    textView.setText(result);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    private String buildResult(String tagObject objectthrows IllegalAccessExceptionNoSuchFieldException {
        Matcher matcher = .matcher(tag);
        while (matcher.find()) {
            String res = matcher.group(0);
            String key = res.substring(1, res.length() - 1);
            if (key.substring(0, 1).equals(".")) {
                Object field = getFieldFromObserver(key.);
                tag = tag.replace(resfield != null ? field.toString() : "");
            } else if (key.substring(0, 8).equals("@string/")) {
                tag = tag.replace(resgetStringResource(key.substring(8)));
            } else {
                Object field = getFieldOrMethodValue(keyobject);
                tag = tag.replace(resfield != null ? field.toString() : "");
            }
        }
        return tag;
    }
    private String getStringResource(String stringName) {
        int resId = .getResources().getIdentifier(stringName"string".getApplicationContext().getPackageName());
        return .getString(resId);
    }
    private List<ObservableWrapperfindObservablesByTag(String tagthrows Exception {
        List<ObservableWrapperlist = new ArrayList<ObservableWrapper>();
        if (tag.matches("\\[.*\\]")) {
            if (. == null) {
                throw new RuntimeException("No data object set. Use JsonObserver.setDataObject() method.");
            }
            tag = tag.substring(1, tag.length() - 1);
            Matcher matcher = .matcher(tag);
            while (matcher.find()) {
                String res = matcher.group(0);
                res = res.substring(1, res.length() - 1);
                if (res.substring(0, 1).equals(".")) {
                    String fields[] = res.split();
                    list.add((ObservableWrapper) ObservableCache.getField(fields[1]).get(.));
                }
            }
        }
        return list;
    }
    @SuppressWarnings("unchecked")
    private void findDataObserver(final Object object) {
        for (final ObservableCache.DataObserverMethod observerMethod : ObservableCache.getDataObserverMethods(object.getClass())) {
            try {
                final Object wrapperOrAdapter = observerMethod.field.get(.);
                if (wrapperOrAdapter instanceof ObservableWrapper) {
                    final ObservableWrapper wrapper = (ObservableWrapperwrapperOrAdapter;
                    WrapObserver observer = new WrapObserver() {
                        @Override
                        public void update(Object data) {
                            try {
                                if (data != null || wrapper.isAllowNull()) {
                                    observerMethod.method.invoke(objectdata);
                                }
                            } catch (Exception e) {
                                JudoException ex;
                                if (e.getCause() != null) {
                                    ex = new JudoException(e.getCause());
                                    ex.setStackTrace(e.getCause().getStackTrace());
                                } else {
                                    ex = new JudoException(e);
                                }
                                if (observerMethod.dataObserver.crashable()) {
                                    throw ex;
                                } else if ( != null) {
                                    .onError(ex);
                                }
                            }
                        }
                    };
                    wrapper.addObserver(observerobserverMethod.dataObserver.onStartup());
                    .add(new Pair<ObservableWrapperWrapObserver>(wrapperobserver));
                } else if (wrapperOrAdapter instanceof Adapter) {
                    final Adapter adapter = (Adapter) wrapperOrAdapter;
                    DataSetObserver dataSetObserver = new DataSetObserver() {
                        @Override
                        public void onChanged() {
                            Object param;
                            if (observerMethod.method.getParameterTypes()[0].isAssignableFrom(List.class)) {
                                List<Objectlist = new ArrayList<Object>();
                                for (int i = 0; i < adapter.getCount(); i++) {
                                    list.add(adapter.getItem(i));
                                }
                                param = list;
                            } else {
                                param = adapter;
                            }
                            try {
                                observerMethod.method.invoke(objectparam);
                            } catch (Exception e) {
                                JudoException ex;
                                if (e.getCause() != null) {
                                    ex = new JudoException(e.getCause());
                                    ex.setStackTrace(e.getCause().getStackTrace());
                                } else {
                                    ex = new JudoException(e);
                                }
                                if (observerMethod.dataObserver.crashable()) {
                                    throw ex;
                                } else if ( != null) {
                                    .onError(ex);
                                }
                            }
                        }
                    };
                    adapter.registerDataSetObserver(dataSetObserver);
                    if (observerMethod.dataObserver.onStartup()) {
                        dataSetObserver.onChanged();
                    }
                    .add(new Pair<Adapter, DataSetObserver>(adapterdataSetObserver));
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
    private Object getFieldFromObserver(String fieldNameObject objectthrows IllegalAccessException {
        String fields[] = fieldName.split();
        ObservableWrapper observableWrapper = (ObservableWrapper) ObservableCache.getField(fields[1]).get(object);
        Object data = observableWrapper.get();
        if (data == null) {
            return "";
        } else {
            return getFieldOrMethodValue(fieldName.substring(fields[1].length() + 2), data);
        }
    }
    private Object getFieldOrMethodValue(String fieldNameObject objectthrows IllegalAccessException {
        String parts[] = fieldName.split();
        Class<?> clazz;
        int i = 0;
        for (String part : parts) {
            clazz = object.getClass();
            try {
                object = ObservableCache.getField(partclazz).get(object);
            } catch (Exception ex) {
                if (i == parts.length - 1) {
                    try {
                        Method method = ObserverAdapterHelper.getMethod(partclazz);
                        if (method.getParameterTypes().length == 1) {
                            return method.invoke(object).toString();
                        } else {
                            return method.invoke(object).toString();
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            i++;
        }
        return object;
    }
    @SuppressWarnings("unchecked")
    public void stop() {
        for (Pair<ObservableWrapperWrapObserverpair : ) {
            pair.first.deleteObserver(pair.second);
        }
        for (Pair<Adapter, DataSetObserver> pair : ) {
            pair.first.unregisterDataSetObserver(pair.second);
        }
        for (Pair<ObservableWrapperWrapObserverpair : .values()) {
            pair.first.deleteObserver(pair.second);
        }
        .clear();
        .clear();
        .clear();
    }
New to GrepCode? Check out our FAQ X