Example usage for android.webkit CookieSyncManager createInstance

List of usage examples for android.webkit CookieSyncManager createInstance

Introduction

In this page you can find the example usage for android.webkit CookieSyncManager createInstance.

Prototype

public static CookieSyncManager createInstance(Context context) 

Source Link

Document

Create a singleton CookieSyncManager within a context

Usage

From source file:com.andrewshu.android.reddit.threads.ThreadsListActivity.java

/**
 * Called when the activity starts up. Do activity initialization
 * here, not in a constructor.//ww  w .  ja v  a2s.c om
 * 
 * @see Activity#onCreate
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    CookieSyncManager.createInstance(getApplicationContext());

    mSettings.loadRedditPreferences(getApplicationContext(), mClient);
    setRequestedOrientation(mSettings.getRotation());
    setTheme(mSettings.getTheme());
    requestWindowFeature(Window.FEATURE_PROGRESS);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

    setContentView(R.layout.threads_list_content);
    registerForContextMenu(getListView());

    if (savedInstanceState != null) {
        if (Constants.LOGGING)
            Log.d(TAG, "using savedInstanceState");
        mSubreddit = savedInstanceState.getString(Constants.SUBREDDIT_KEY);
        if (mSubreddit == null)
            mSubreddit = mSettings.getHomepage();
        mAfter = savedInstanceState.getString(Constants.AFTER_KEY);
        mBefore = savedInstanceState.getString(Constants.BEFORE_KEY);
        mCount = savedInstanceState.getInt(Constants.THREAD_COUNT_KEY);
        mLastAfter = savedInstanceState.getString(Constants.LAST_AFTER_KEY);
        mLastBefore = savedInstanceState.getString(Constants.LAST_BEFORE_KEY);
        mLastCount = savedInstanceState.getInt(Constants.THREAD_LAST_COUNT_KEY);
        mSortByUrl = savedInstanceState.getString(Constants.ThreadsSort.SORT_BY_KEY);
        mJumpToThreadId = savedInstanceState.getString(Constants.JUMP_TO_THREAD_ID_KEY);
        mVoteTargetThing = savedInstanceState.getParcelable(Constants.VOTE_TARGET_THING_INFO_KEY);

        // try to restore mThreadsList using getLastNonConfigurationInstance()
        // (separate function to avoid a compiler warning casting ArrayList<ThingInfo>
        restoreLastNonConfigurationInstance();
        if (mThreadsList == null) {
            // Load previous view of threads
            if (mLastAfter != null) {
                new MyDownloadThreadsTask(mSubreddit, mLastAfter, null, mLastCount).execute();
            } else if (mLastBefore != null) {
                new MyDownloadThreadsTask(mSubreddit, null, mLastBefore, mLastCount).execute();
            } else {
                new MyDownloadThreadsTask(mSubreddit).execute();
            }
        } else {
            // Orientation change. Use prior instance.
            resetUI(new ThreadsListAdapter(this, mThreadsList));
            if (Constants.FRONTPAGE_STRING.equals(mSubreddit))
                setTitle("reddit.com: what's new online!");
            else
                setTitle("/r/" + mSubreddit.trim());
        }
    }
    // Handle subreddit Uri passed via Intent
    else if (getIntent().getData() != null) {
        Matcher redditContextMatcher = REDDIT_PATH_PATTERN.matcher(getIntent().getData().getPath());
        if (redditContextMatcher.matches()) {
            new MyDownloadThreadsTask(redditContextMatcher.group(1)).execute();
        } else {
            new MyDownloadThreadsTask(mSettings.getHomepage()).execute();
        }
    }
    // No subreddit specified by Intent, so load the user's home reddit
    else {
        new MyDownloadThreadsTask(mSettings.getHomepage()).execute();
    }
}

From source file:com.popdeem.sdk.uikit.fragment.PDUIInstagramLoginFragment.java

@SuppressWarnings("deprecation")
private void clearCookies() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
        CookieManager.getInstance().removeAllCookies(null);
        CookieManager.getInstance().flush();
    } else {//from w  w w  .j  ava2  s. c o  m
        CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(getActivity());
        cookieSyncManager.startSync();
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
        cookieManager.removeSessionCookie();
        cookieSyncManager.stopSync();
        cookieSyncManager.sync();
    }
}

From source file:at.ac.uniklu.mobile.sportal.WebViewActivity.java

@SuppressLint("SetJavaScriptEnabled")
@Override// www.j av a  2s. com
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String targetUrl = getIntent().getStringExtra(URL);
    if (targetUrl == null || targetUrl.length() == 0) {
        // if there's no URL, close the activity
        finish();
    }

    setContentView(R.layout.webview);
    mActionBar = new ActionBarHelper(this).setupHeader().addActionRefresh();

    // set header title or hide header if no title is given
    String title = getIntent().getStringExtra(TITLE);
    if (title != null) {
        ((TextView) findViewById(R.id.view_title)).setText(title);
    } else {
        findViewById(R.id.actionbar).setVisibility(View.GONE);
    }

    // Moodle 2.0 uses SSO/CAS authentication
    mSSO = getIntent().getBooleanExtra(SSO, false);

    // the moodle hack is only needed until Android 2.3 (or maybe 3.x? - not tested)
    // Android 4.0 has the redirect history entry problem solved
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
        mExecuteMoodleHack = getIntent().getBooleanExtra(MOODLE_HACK, false);
    }

    mWebView = (WebView) findViewById(R.id.web_view);
    //mWebView.setBackgroundColor(Color.BLACK); // black color messes up the CAS login page
    mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); // http://stackoverflow.com/questions/3998916/android-webview-leaves-space-for-scrollbar
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setLightTouchEnabled(true);
    mWebView.getSettings().setLoadWithOverviewMode(true);
    mWebView.getSettings().setBuiltInZoomControls(true);
    mWebView.getSettings().setUseWideViewPort(true);

    // setup custom webview client that shows a progress dialog while loading
    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("https://sso.uni-klu.ac.at") || url.startsWith("https://sso.aau.at")
                    || url.startsWith("https://campus.aau.at") || url.startsWith("https://moodle.aau.at")) {
                return false;
            } else if (url.startsWith("http://campus-gis.aau.at/")) {
                Log.d(TAG, "REDIRECT TO MAP");
                String roomParameter = "curRouteTo=";
                int index = url.indexOf(roomParameter);
                if (index > -1) {
                    MapUtils.openMapAndShowRoom(WebViewActivity.this,
                            url.substring(index + roomParameter.length()));
                }
                return true;
            }

            // open external websites in browser
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(url));
            startActivity(i);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            progressNotificationOn();
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            progressNotificationOff();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            progressNotificationOff();

            /*
             *  the first page of moodle opens through a redirect so we need to clear the first history
             *  entry to avoid execution of the redirect when going back through the history with the back button
             */
            if (mExecuteMoodleHack && mWebView.canGoBack()) {
                mWebView.clearHistory();
                mExecuteMoodleHack = false;
            } else {
                mIsFirstPage = false;
            }
        }
    });

    mWebView.setDownloadListener(new DownloadListener() {
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                long contentLength) {
            Analytics.onEvent(Analytics.EVENT_WEB_COURSEMOODLE_DOWNLOAD);
            Uri uri = Uri.parse(url);
            MoodleDownloadHelper.download(WebViewActivity.this, uri,
                    Utils.getContentDispositionOrUrlFilename(contentDisposition, uri));
        }
    });

    // set session cookie
    // http://stackoverflow.com/questions/1652850/android-webview-cookie-problem
    // http://android.joao.jp/2010/11/cookiemanager-and-removeallcookie.html
    if (Studentportal.getSportalClient().isSessionCookieAvailable()) {
        CookieSyncManager.createInstance(this);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        //cookieManager.removeSessionCookie(); // NOTE when calling this method the cookies get removed after the next setCookie() gets called

        Cookie sessionCookie = Studentportal.getSportalClient().getSessionCookie();
        cookieManager.setCookie(sessionCookie.getDomain(), Utils.cookieHeaderString(sessionCookie));

        if (mSSO) {
            // set SSO/CAS cookie
            Cookie ssoCookie = Studentportal.getSportalClient().getCookie("CASTGC");
            if (ssoCookie != null) {
                cookieManager.setCookie(ssoCookie.getDomain(), Utils.cookieHeaderString(ssoCookie));
            }
        }

        CookieSyncManager.getInstance().sync();
    }

    mIsFirstPage = true;
    mWebView.loadUrl(targetUrl);
}

From source file:com.andrewshu.android.reddit.user.ProfileActivity.java

/**
 * Called when the activity starts up. Do activity initialization
 * here, not in a constructor.// w  w  w. jav  a2  s .  c om
 * 
 * @see Activity#onCreate
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    CookieSyncManager.createInstance(getApplicationContext());

    mSettings.loadRedditPreferences(this, mClient);
    setRequestedOrientation(mSettings.getRotation());
    setTheme(mSettings.getTheme());
    requestWindowFeature(Window.FEATURE_PROGRESS);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

    setContentView(R.layout.profile_list_content);
    registerForContextMenu(getListView());

    if (savedInstanceState != null) {
        if (Constants.LOGGING)
            Log.d(TAG, "using savedInstanceState");
        mUsername = savedInstanceState.getString(Constants.USERNAME_KEY);
        mAfter = savedInstanceState.getString(Constants.AFTER_KEY);
        mBefore = savedInstanceState.getString(Constants.BEFORE_KEY);
        mCount = savedInstanceState.getInt(Constants.THREAD_COUNT_KEY);
        mLastAfter = savedInstanceState.getString(Constants.LAST_AFTER_KEY);
        mLastBefore = savedInstanceState.getString(Constants.LAST_BEFORE_KEY);
        mLastCount = savedInstanceState.getInt(Constants.THREAD_LAST_COUNT_KEY);
        mKarma = savedInstanceState.getIntArray(Constants.KARMA_KEY);
        mSortByUrl = savedInstanceState.getString(Constants.CommentsSort.SORT_BY_KEY);
        mJumpToThreadId = savedInstanceState.getString(Constants.JUMP_TO_THREAD_ID_KEY);
        mVoteTargetThingInfo = savedInstanceState.getParcelable(Constants.VOTE_TARGET_THING_INFO_KEY);

        // try to restore mThingsList using getLastNonConfigurationInstance()
        // (separate function to avoid a compiler warning casting ArrayList<ThingInfo>
        restoreLastNonConfigurationInstance();
        if (mThingsList == null) {
            // Load previous page of profile items
            if (mLastAfter != null) {
                new DownloadProfileTask(mUsername, mLastAfter, null, mLastCount).execute();
            } else if (mLastBefore != null) {
                new DownloadProfileTask(mUsername, null, mLastBefore, mLastCount).execute();
            } else {
                new DownloadProfileTask(mUsername).execute();
            }
        } else {
            // Orientation change. Use prior instance.
            resetUI(new ThingsListAdapter(this, mThingsList));
            setTitle(mUsername + "'s profile");
        }
        return;
    }
    // Handle subreddit Uri passed via Intent
    else if (getIntent().getData() != null) {
        Matcher userPathMatcher = USER_PATH_PATTERN.matcher(getIntent().getData().getPath());
        if (userPathMatcher.matches()) {
            mUsername = userPathMatcher.group(1);
            new DownloadProfileTask(mUsername).execute();
            return;
        }
    }

    // No username specified by Intent, so load the logged in user's profile
    if (mSettings.isLoggedIn()) {
        mUsername = mSettings.getUsername();
        new DownloadProfileTask(mUsername).execute();
        return;
    }

    // Can't find a username to use. Quit.
    if (Constants.LOGGING)
        Log.e(TAG, "Could not find a username to use for ProfileActivity");
    finish();
}

From source file:com.andrewshu.android.reddit.profile.ProfileActivity.java

/**
 * Called when the activity starts up. Do activity initialization
 * here, not in a constructor.//  w  w w . j av a  2s  .  c om
 * 
 * @see Activity#onCreate
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    CookieSyncManager.createInstance(getApplicationContext());

    mSettings.loadRedditPreferences(this, mClient);
    setRequestedOrientation(mSettings.getRotation());
    setTheme(mSettings.getTheme());
    requestWindowFeature(Window.FEATURE_PROGRESS);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

    setContentView(R.layout.profile_list_content);

    if (savedInstanceState != null) {
        if (Constants.LOGGING)
            Log.d(TAG, "using savedInstanceState");
        mUsername = savedInstanceState.getString(Constants.USERNAME_KEY);
        mAfter = savedInstanceState.getString(Constants.AFTER_KEY);
        mBefore = savedInstanceState.getString(Constants.BEFORE_KEY);
        mCount = savedInstanceState.getInt(Constants.THREAD_COUNT_KEY);
        mLastAfter = savedInstanceState.getString(Constants.LAST_AFTER_KEY);
        mLastBefore = savedInstanceState.getString(Constants.LAST_BEFORE_KEY);
        mLastCount = savedInstanceState.getInt(Constants.THREAD_LAST_COUNT_KEY);
        mKarma = savedInstanceState.getStringArray(Constants.KARMA_KEY);
        mSortByUrl = savedInstanceState.getString(Constants.CommentsSort.SORT_BY_KEY);
        mJumpToThreadId = savedInstanceState.getString(Constants.JUMP_TO_THREAD_ID_KEY);
        mVoteTargetThingInfo = savedInstanceState.getParcelable(Constants.VOTE_TARGET_THING_INFO_KEY);

        // try to restore mThingsList using getLastNonConfigurationInstance()
        // (separate function to avoid a compiler warning casting ArrayList<ThingInfo>
        restoreLastNonConfigurationInstance();
        if (mThingsList == null) {
            // Load previous page of profile items
            if (mLastAfter != null) {
                new DownloadProfileTask(mUsername, mLastAfter, null, mLastCount).execute();
            } else if (mLastBefore != null) {
                new DownloadProfileTask(mUsername, null, mLastBefore, mLastCount).execute();
            } else {
                new DownloadProfileTask(mUsername).execute();
            }
        } else {
            // Orientation change. Use prior instance.
            resetUI(new ThingsListAdapter(this, mThingsList));
            setTitle(mUsername + "'s profile");
        }
        return;
    }
    // Handle subreddit Uri passed via Intent
    else if (getIntent().getData() != null) {
        Matcher userPathMatcher = USER_PATH_PATTERN.matcher(getIntent().getData().getPath());
        if (userPathMatcher.matches()) {
            mUsername = userPathMatcher.group(1);
            new DownloadProfileTask(mUsername).execute();
            return;
        }
    }

    // No username specified by Intent, so load the logged in user's profile
    if (mSettings.isLoggedIn()) {
        mUsername = mSettings.getUsername();
        new DownloadProfileTask(mUsername).execute();
        return;
    }

    // Can't find a username to use. Quit.
    if (Constants.LOGGING)
        Log.e(TAG, "Could not find a username to use for ProfileActivity");
    finish();
}

From source file:com.msdpe.authenticationdemo.AuthService.java

/**
 * Handles logging the user out including:
 * -deleting cookies so their login with a provider won't be cached in the web view
 * -removing the userdata from the shared preferences
 * -setting the current user object on the client to logged out
 * -optionally redirects to the login page if requested
 * @param shouldRedirectToLogin/*from  w  w w  .j  av  a  2 s.c  o  m*/
 */
public void logout(boolean shouldRedirectToLogin) {
    //Clear the cookies so they won't auto login to a provider again
    CookieSyncManager.createInstance(mContext);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.removeAllCookie();
    //Clear the user id and token from the shared preferences
    SharedPreferences settings = mContext.getSharedPreferences("UserData", 0);
    SharedPreferences.Editor preferencesEditor = settings.edit();
    preferencesEditor.clear();
    preferencesEditor.commit();
    //Clear the user and return to the auth activity
    mClient.logout();
    //Take the user back to the auth activity to relogin if requested
    if (shouldRedirectToLogin) {
        Intent logoutIntent = new Intent(mContext, AuthenticationActivity.class);
        logoutIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(logoutIntent);
    }
}

From source file:com.danvelazco.fbwrapper.activity.BaseFacebookWebViewActivity.java

/**
 * {@inheritDoc}//  ww w.  j av a2 s. c om
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Create the activity and set the layout
    onActivityCreated();

    mConnectivityManager = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);

    mWebView = (FacebookWebView) findViewById(R.id.webview);
    mWebView.setCustomContentView((FrameLayout) findViewById(R.id.fullscreen_custom_content));
    mWebView.setWebChromeClientListener(this);
    mWebView.setWebViewClientListener(this);
    mWebSettings = mWebView.getWebSettings();

    mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);

    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
    mSwipeRefreshLayout.setOnRefreshListener(this);
    // Set the database path for this WebView so that
    // HTML5 Storage API works properly
    mWebSettings.setAppCacheEnabled(true);
    mWebSettings.setDatabaseEnabled(true);

    // Create a CookieSyncManager instance and keep a reference of it
    mCookieSyncManager = CookieSyncManager.createInstance(this);

    registerForContextMenu(mWebView);

    // Have the activity open the proper URL
    onWebViewInit(savedInstanceState);
}

From source file:com.awadev.itslearningautologin.MainActivity.java

private void initUI() {
    // Navigation drawer
    mTitle = mDrawerTitle = getTitle();/*from  w w  w  . j  ava2  s . co  m*/
    String[] mPlanetTitles = getResources().getStringArray(R.array.planets_array);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    // set a custom shadow that overlays the main content when the drawer opens
    //mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    // set up the drawer's list view with items and click listener
    mDrawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mPlanetTitles));
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

    // enable ActionBar app icon to behave as action to toggle nav drawer
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the sliding drawer and the action bar app icon
    mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
            mDrawerLayout, /* DrawerLayout object */
            R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
            R.string.drawer_open, /* "open drawer" description for accessibility */
            R.string.drawer_close /* "close drawer" description for accessibility */
    ) {
        public void onDrawerClosed(View view) {
            getSupportActionBar().setTitle(mTitle);
            supportInvalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }

        public void onDrawerOpened(View drawerView) {
            getSupportActionBar().setTitle(mDrawerTitle);
            supportInvalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);
    // End navigation drawer

    webViewPlaceholder = ((RelativeLayout) findViewById(R.id.webViewPlaceholder));

    if (mWebView == null) {
        // Set cookies
        mWebView = new WebView(this);
        mWebView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));

        CookieSyncManager.createInstance(this);
        WebComponent.copyCookies(CookieManager.getInstance());

        // Make the WebView behave like we want
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setSupportMultipleWindows(true);
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        mWebView.getSettings().setUserAgentString("itsLearning login - Android");

        mWebView.setWebViewClient(new CustomWebClient());

        // Load!
        String url = ((MainApplication) getApplication()).getLoadUrl();
        if (url != null) {
            mWebView.loadUrl(url);
            ((MainApplication) getApplication()).setLoadUrl(null);
        } else
            mWebView.loadUrl(((MainApplication) getApplication()).baseURL + "/DashboardMenu.aspx");
    }
    // Attach the WebView to its placeholder
    webViewPlaceholder.addView(mWebView);
}

From source file:in.shick.diode.threads.ThreadsListActivity.java

/**
 * Called when the activity starts up. Do activity initialization
 * here, not in a constructor./*  ww w.  j  av  a  2  s .  c  o  m*/
 *
 * @see Activity#onCreate
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    CookieSyncManager.createInstance(getApplicationContext());

    mSettings.loadRedditPreferences(getApplicationContext());
    setRequestedOrientation(mSettings.getRotation());
    setTheme(mSettings.getTheme());
    requestWindowFeature(Window.FEATURE_PROGRESS);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

    setContentView(R.layout.threads_list_content);
    swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
    swipeLayout.setOnRefreshListener(this);
    swipeLayout.setColorScheme(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
            android.R.color.holo_orange_light, android.R.color.holo_red_light);

    registerForContextMenu(getListView());

    if (savedInstanceState != null) {
        if (Constants.LOGGING)
            Log.d(TAG, "using savedInstanceState");
        mSubreddit = savedInstanceState.getString(Constants.SUBREDDIT_KEY);
        if (mSubreddit == null)
            mSubreddit = mSettings.getHomepage();
        mAfter = savedInstanceState.getString(Constants.AFTER_KEY);
        mBefore = savedInstanceState.getString(Constants.BEFORE_KEY);
        mCount = savedInstanceState.getInt(Constants.THREAD_COUNT_KEY);
        mLastAfter = savedInstanceState.getString(Constants.LAST_AFTER_KEY);
        mLastBefore = savedInstanceState.getString(Constants.LAST_BEFORE_KEY);
        mLastCount = savedInstanceState.getInt(Constants.THREAD_LAST_COUNT_KEY);
        mSortByUrl = savedInstanceState.getString(Constants.ThreadsSort.SORT_BY_KEY);
        mJumpToThreadId = savedInstanceState.getString(Constants.JUMP_TO_THREAD_ID_KEY);
        mSearchQuery = savedInstanceState.getString(Constants.QUERY_KEY);
        mVoteTargetThing = savedInstanceState.getParcelable(Constants.VOTE_TARGET_THING_INFO_KEY);

        // try to restore mThreadsList using getLastNonConfigurationInstance()
        // (separate function to avoid a compiler warning casting ArrayList<ThingInfo>
        restoreLastNonConfigurationInstance();

        if (mObjectStates == null) {
            mObjectStates = new ObjectStates();
            if (mObjectStates.mThreadsList == null) {
                // Load previous view of threads
                if (mLastAfter != null) {
                    mObjectStates.mCurrentDownloadThreadsTask = new MyDownloadThreadsTask(mSubreddit,
                            mLastAfter, null, mLastCount);
                } else if (mLastBefore != null) {
                    mObjectStates.mCurrentDownloadThreadsTask = new MyDownloadThreadsTask(mSubreddit, null,
                            mLastBefore, mLastCount);
                } else {
                    mObjectStates.mCurrentDownloadThreadsTask = new MyDownloadThreadsTask(mSubreddit);
                }
                mObjectStates.mCurrentDownloadThreadsTask.execute();
            }
        } else {
            if (mObjectStates.mCurrentDownloadThreadsTask.getStatus() != Status.FINISHED) {
                mObjectStates.mCurrentDownloadThreadsTask.attach(this);
            } else {
                // Orientation change. Use prior instance.
                resetUI(new ThreadsListAdapter(this, mObjectStates.mThreadsList));
                setWindowTitle();
            }
        }
    }
    // Handle subreddit Uri passed via Intent
    else if (getIntent().getData() != null) {
        mObjectStates = new ObjectStates();
        Matcher redditContextMatcher = REDDIT_PATH_PATTERN.matcher(getIntent().getData().getPath());
        if (redditContextMatcher.matches()) {
            mObjectStates.mCurrentDownloadThreadsTask = new MyDownloadThreadsTask(
                    redditContextMatcher.group(1));
        } else if (getIntent().getData().toString().toLowerCase().endsWith("/saved.json")) {
            mSavedUri = getIntent().getData();
            mObjectStates.mCurrentDownloadThreadsTask = new MyDownloadThreadsTask(getIntent().getData());
        } else {
            mObjectStates.mCurrentDownloadThreadsTask = new MyDownloadThreadsTask(mSettings.getHomepage());
        }
        mObjectStates.mCurrentDownloadThreadsTask.execute();
    }
    // No subreddit specified by Intent, so load the user's home reddit
    else {
        mObjectStates = new ObjectStates();
        mObjectStates.mCurrentDownloadThreadsTask = new MyDownloadThreadsTask(mSettings.getHomepage());
        mObjectStates.mCurrentDownloadThreadsTask.execute();
    }
}

From source file:com.andrewshu.android.reddit.comments.CommentsListActivity.java

/**
 * Called when the activity starts up. Do activity initialization
 * here, not in a constructor.//from w  w w .  jav  a 2  s.c o  m
 * 
 * @see Activity#onCreate
 */
@SuppressWarnings("unchecked")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    CookieSyncManager.createInstance(getApplicationContext());

    mSettings.loadRedditPreferences(this, mClient);

    setRequestedOrientation(mSettings.getRotation());
    setTheme(mSettings.getTheme());
    requestWindowFeature(Window.FEATURE_PROGRESS);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

    setContentView(R.layout.comments_list_content);
    registerForContextMenu(getListView());

    if (savedInstanceState != null) {
        mReplyTargetName = savedInstanceState.getString(Constants.REPLY_TARGET_NAME_KEY);
        mReportTargetName = savedInstanceState.getString(Constants.REPORT_TARGET_NAME_KEY);
        mEditTargetBody = savedInstanceState.getString(Constants.EDIT_TARGET_BODY_KEY);
        mDeleteTargetKind = savedInstanceState.getString(Constants.DELETE_TARGET_KIND_KEY);
        mThreadTitle = savedInstanceState.getString(Constants.THREAD_TITLE_KEY);
        mSubreddit = savedInstanceState.getString(Constants.SUBREDDIT_KEY);
        mThreadId = savedInstanceState.getString(Constants.THREAD_ID_KEY);
        mVoteTargetThing = savedInstanceState.getParcelable(Constants.VOTE_TARGET_THING_INFO_KEY);

        if (mThreadTitle != null) {
            setTitle(mThreadTitle + " : " + mSubreddit);
        }

        mCommentsList = (ArrayList<ThingInfo>) getLastNonConfigurationInstance();
        if (mCommentsList == null) {
            getNewDownloadCommentsTask().execute(Constants.DEFAULT_COMMENT_DOWNLOAD_LIMIT);
        } else {
            // Orientation change. Use prior instance.
            resetUI(new CommentsListAdapter(this, mCommentsList));
        }
    }

    // No saved state; use info from Intent.getData()
    else {
        String commentPath;
        String commentQuery;
        String jumpToCommentId = null;
        int jumpToCommentContext = 0;
        // We get the URL through getIntent().getData()
        Uri data = getIntent().getData();
        if (data != null) {
            // Comment path: a URL pointing to a thread or a comment in a thread.
            commentPath = data.getPath();
            commentQuery = data.getQuery();
        } else {
            if (Constants.LOGGING)
                Log.e(TAG, "Quitting because no subreddit and thread id data was passed into the Intent.");
            finish();
            return;
        }

        if (commentPath != null) {
            if (Constants.LOGGING)
                Log.d(TAG, "comment path: " + commentPath);

            if (Util.isRedditShortenedUri(data)) {
                // http://redd.it/abc12
                mThreadId = commentPath.substring(1);
            } else {
                // http://www.reddit.com/...
                Matcher m = COMMENT_PATH_PATTERN.matcher(commentPath);
                if (m.matches()) {
                    mSubreddit = m.group(1);
                    mThreadId = m.group(2);
                    jumpToCommentId = m.group(3);
                }
            }
        } else {
            if (Constants.LOGGING)
                Log.e(TAG, "Quitting because of bad comment path.");
            finish();
            return;
        }

        if (commentQuery != null) {
            Matcher m = COMMENT_CONTEXT_PATTERN.matcher(commentQuery);
            if (m.find()) {
                jumpToCommentContext = m.group(1) != null ? Integer.valueOf(m.group(1)) : 0;
            }
        }

        // Extras: subreddit, threadTitle, numComments
        // subreddit is not always redundant to Intent.getData(),
        // since URL does not always contain the subreddit. (e.g., self posts)
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            // subreddit could have already been set from the Intent.getData. don't overwrite with null here!
            String subreddit = extras.getString(Constants.EXTRA_SUBREDDIT);
            if (subreddit != null)
                mSubreddit = subreddit;
            // mThreadTitle has not been set yet, so no need for null check before setting it
            mThreadTitle = extras.getString(Constants.EXTRA_TITLE);
            if (mThreadTitle != null) {
                setTitle(mThreadTitle + " : " + mSubreddit);
            }
            // TODO: use extras.getInt(Constants.EXTRA_NUM_COMMENTS) somehow
        }

        if (!StringUtils.isEmpty(jumpToCommentId)) {
            getNewDownloadCommentsTask().prepareLoadAndJumpToComment(jumpToCommentId, jumpToCommentContext)
                    .execute(Constants.DEFAULT_COMMENT_DOWNLOAD_LIMIT);
        } else {
            getNewDownloadCommentsTask().execute(Constants.DEFAULT_COMMENT_DOWNLOAD_LIMIT);
        }
    }
}