code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.widget; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; /** * Custom layout that arranges children in a grid-like manner, optimizing for even horizontal and * vertical whitespace. */ public class DashboardLayout extends ViewGroup { private static final int UNEVEN_GRID_PENALTY_MULTIPLIER = 10; private int mMaxChildWidth = 0; private int mMaxChildHeight = 0; public DashboardLayout(Context context) { super(context, null); } public DashboardLayout(Context context, AttributeSet attrs) { super(context, attrs, 0); } public DashboardLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { mMaxChildWidth = 0; mMaxChildHeight = 0; // Measure once to find the maximum child size. int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec( MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.AT_MOST); int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec( MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.AT_MOST); final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } child.measure(childWidthMeasureSpec, childHeightMeasureSpec); mMaxChildWidth = Math.max(mMaxChildWidth, child.getMeasuredWidth()); mMaxChildHeight = Math.max(mMaxChildHeight, child.getMeasuredHeight()); } // Measure again for each child to be exactly the same size. childWidthMeasureSpec = MeasureSpec.makeMeasureSpec( mMaxChildWidth, MeasureSpec.EXACTLY); childHeightMeasureSpec = MeasureSpec.makeMeasureSpec( mMaxChildHeight, MeasureSpec.EXACTLY); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } setMeasuredDimension( resolveSize(mMaxChildWidth, widthMeasureSpec), resolveSize(mMaxChildHeight, heightMeasureSpec)); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int width = r - l; int height = b - t; final int count = getChildCount(); // Calculate the number of visible children. int visibleCount = 0; for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } ++visibleCount; } if (visibleCount == 0) { return; } // Calculate what number of rows and columns will optimize for even horizontal and // vertical whitespace between items. Start with a 1 x N grid, then try 2 x N, and so on. int bestSpaceDifference = Integer.MAX_VALUE; int spaceDifference; // Horizontal and vertical space between items int hSpace = 0; int vSpace = 0; int cols = 1; int rows; while (true) { rows = (visibleCount - 1) / cols + 1; hSpace = ((width - mMaxChildWidth * cols) / (cols + 1)); vSpace = ((height - mMaxChildHeight * rows) / (rows + 1)); spaceDifference = Math.abs(vSpace - hSpace); if (rows * cols != visibleCount) { spaceDifference *= UNEVEN_GRID_PENALTY_MULTIPLIER; } if (spaceDifference < bestSpaceDifference) { // Found a better whitespace squareness/ratio bestSpaceDifference = spaceDifference; // If we found a better whitespace squareness and there's only 1 row, this is // the best we can do. if (rows == 1) { break; } } else { // This is a worse whitespace ratio, use the previous value of cols and exit. --cols; rows = (visibleCount - 1) / cols + 1; hSpace = ((width - mMaxChildWidth * cols) / (cols + 1)); vSpace = ((height - mMaxChildHeight * rows) / (rows + 1)); break; } ++cols; } // Lay out children based on calculated best-fit number of rows and cols. // If we chose a layout that has negative horizontal or vertical space, force it to zero. hSpace = Math.max(0, hSpace); vSpace = Math.max(0, vSpace); // Re-use width/height variables to be child width/height. width = (width - hSpace * (cols + 1)) / cols; height = (height - vSpace * (rows + 1)) / rows; int left, top; int col, row; int visibleIndex = 0; for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } row = visibleIndex / cols; col = visibleIndex % cols; left = hSpace * (col + 1) + width * col; top = vSpace * (row + 1) + height * row; child.layout(left, top, (hSpace == 0 && col == cols - 1) ? r : (left + width), (vSpace == 0 && row == rows - 1) ? b : (top + height)); ++visibleIndex; } } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.widget; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.util.UIUtils; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.FontMetricsInt; import android.graphics.Paint.Style; import android.graphics.Typeface; import android.text.format.Time; import android.util.AttributeSet; import android.view.View; /** * Custom view that draws a vertical time "ruler" representing the chronological * progression of a single day. Usually shown along with {@link BlockView} * instances to give a spatial sense of time. */ public class TimeRulerView extends View { private int mHeaderWidth = 70; private int mHourHeight = 90; private boolean mHorizontalDivider = true; private int mLabelTextSize = 20; private int mLabelPaddingLeft = 8; private int mLabelColor = Color.BLACK; private int mDividerColor = Color.LTGRAY; private int mStartHour = 0; private int mEndHour = 23; public TimeRulerView(Context context) { this(context, null); } public TimeRulerView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public TimeRulerView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TimeRulerView, defStyle, 0); mHeaderWidth = a.getDimensionPixelSize(R.styleable.TimeRulerView_headerWidth, mHeaderWidth); mHourHeight = a .getDimensionPixelSize(R.styleable.TimeRulerView_hourHeight, mHourHeight); mHorizontalDivider = a.getBoolean(R.styleable.TimeRulerView_horizontalDivider, mHorizontalDivider); mLabelTextSize = a.getDimensionPixelSize(R.styleable.TimeRulerView_labelTextSize, mLabelTextSize); mLabelPaddingLeft = a.getDimensionPixelSize(R.styleable.TimeRulerView_labelPaddingLeft, mLabelPaddingLeft); mLabelColor = a.getColor(R.styleable.TimeRulerView_labelColor, mLabelColor); mDividerColor = a.getColor(R.styleable.TimeRulerView_dividerColor, mDividerColor); mStartHour = a.getInt(R.styleable.TimeRulerView_startHour, mStartHour); mEndHour = a.getInt(R.styleable.TimeRulerView_endHour, mEndHour); a.recycle(); } /** * Return the vertical offset (in pixels) for a requested time (in * milliseconds since epoch). */ public int getTimeVerticalOffset(long timeMillis) { Time time = new Time(UIUtils.CONFERENCE_TIME_ZONE.getID()); time.set(timeMillis); final int minutes = ((time.hour - mStartHour) * 60) + time.minute; return (minutes * mHourHeight) / 60; } @Override protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int hours = mEndHour - mStartHour; int width = mHeaderWidth; int height = mHourHeight * hours; setMeasuredDimension(resolveSize(width, widthMeasureSpec), resolveSize(height, heightMeasureSpec)); } private Paint mDividerPaint = new Paint(); private Paint mLabelPaint = new Paint(); @Override protected synchronized void onDraw(Canvas canvas) { super.onDraw(canvas); final int hourHeight = mHourHeight; final Paint dividerPaint = mDividerPaint; dividerPaint.setColor(mDividerColor); dividerPaint.setStyle(Style.FILL); final Paint labelPaint = mLabelPaint; labelPaint.setColor(mLabelColor); labelPaint.setTextSize(mLabelTextSize); labelPaint.setTypeface(Typeface.DEFAULT_BOLD); labelPaint.setAntiAlias(true); final FontMetricsInt metrics = labelPaint.getFontMetricsInt(); final int labelHeight = Math.abs(metrics.ascent); final int labelOffset = labelHeight + mLabelPaddingLeft; final int right = getRight(); // Walk left side of canvas drawing timestamps final int hours = mEndHour - mStartHour; for (int i = 0; i < hours; i++) { final int dividerY = hourHeight * i; final int nextDividerY = hourHeight * (i + 1); canvas.drawLine(0, dividerY, right, dividerY, dividerPaint); // draw text title for timestamp canvas.drawRect(0, dividerY, mHeaderWidth, nextDividerY, dividerPaint); // TODO: localize these labels better, including handling // 24-hour mode when set in framework. final int hour = mStartHour + i; String label; if (hour == 0) { label = "12am"; } else if (hour <= 11) { label = hour + "am"; } else if (hour == 12) { label = "12pm"; } else { label = (hour - 12) + "pm"; } final float labelWidth = labelPaint.measureText(label); canvas.drawText(label, 0, label.length(), mHeaderWidth - labelWidth - mLabelPaddingLeft, dividerY + labelOffset, labelPaint); } } public int getHeaderWidth() { return mHeaderWidth; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.widget; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.util.UIUtils; import android.content.Context; import android.graphics.Color; import android.graphics.PorterDuff; import android.graphics.drawable.LayerDrawable; import android.text.format.DateUtils; import android.widget.Button; import java.util.TimeZone; /** * Custom view that represents a {@link Blocks#BLOCK_ID} instance, including its * title and time span that it occupies. Usually organized automatically by * {@link BlocksLayout} to match up against a {@link TimeRulerView} instance. */ public class BlockView extends Button { private static final int TIME_STRING_FLAGS = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_WEEKDAY | DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_ABBREV_TIME; private final String mBlockId; private final String mTitle; private final long mStartTime; private final long mEndTime; private final boolean mContainsStarred; private final int mColumn; public BlockView(Context context, String blockId, String title, long startTime, long endTime, boolean containsStarred, int column) { super(context); mBlockId = blockId; mTitle = title; mStartTime = startTime; mEndTime = endTime; mContainsStarred = containsStarred; mColumn = column; setText(mTitle); // TODO: turn into color state list with layers? int textColor = Color.WHITE; int accentColor = -1; switch (mColumn) { case 0: accentColor = getResources().getColor(R.color.block_column_1); break; case 1: accentColor = getResources().getColor(R.color.block_column_2); break; case 2: accentColor = getResources().getColor(R.color.block_column_3); break; } LayerDrawable buttonDrawable = (LayerDrawable) context.getResources().getDrawable(R.drawable.btn_block); buttonDrawable.getDrawable(0).setColorFilter(accentColor, PorterDuff.Mode.SRC_ATOP); buttonDrawable.getDrawable(1).setAlpha(mContainsStarred ? 255 : 0); setTextColor(textColor); setBackgroundDrawable(buttonDrawable); } public String getBlockId() { return mBlockId; } public String getBlockTimeString() { TimeZone.setDefault(UIUtils.CONFERENCE_TIME_ZONE); return DateUtils.formatDateTime(getContext(), mStartTime, TIME_STRING_FLAGS); } public long getStartTime() { return mStartTime; } public long getEndTime() { return mEndTime; } public int getColumn() { return mColumn; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.widget; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.util.UIUtils; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; /** * Custom layout that contains and organizes a {@link TimeRulerView} and several * instances of {@link BlockView}. Also positions current "now" divider using * {@link R.id#blocks_now} view when applicable. */ public class BlocksLayout extends ViewGroup { private int mColumns = 3; private TimeRulerView mRulerView; private View mNowView; public BlocksLayout(Context context) { this(context, null); } public BlocksLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public BlocksLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BlocksLayout, defStyle, 0); mColumns = a.getInt(R.styleable.TimeRulerView_headerWidth, mColumns); a.recycle(); } private void ensureChildren() { mRulerView = (TimeRulerView) findViewById(R.id.blocks_ruler); if (mRulerView == null) { throw new IllegalStateException("Must include a R.id.blocks_ruler view."); } mRulerView.setDrawingCacheEnabled(true); mNowView = findViewById(R.id.blocks_now); if (mNowView == null) { throw new IllegalStateException("Must include a R.id.blocks_now view."); } mNowView.setDrawingCacheEnabled(true); } /** * Remove any {@link BlockView} instances, leaving only * {@link TimeRulerView} remaining. */ public void removeAllBlocks() { ensureChildren(); removeAllViews(); addView(mRulerView); addView(mNowView); } public void addBlock(BlockView blockView) { blockView.setDrawingCacheEnabled(true); addView(blockView, 1); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { ensureChildren(); mRulerView.measure(widthMeasureSpec, heightMeasureSpec); mNowView.measure(widthMeasureSpec, heightMeasureSpec); final int width = mRulerView.getMeasuredWidth(); final int height = mRulerView.getMeasuredHeight(); setMeasuredDimension(resolveSize(width, widthMeasureSpec), resolveSize(height, heightMeasureSpec)); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { ensureChildren(); final TimeRulerView rulerView = mRulerView; final int headerWidth = rulerView.getHeaderWidth(); final int columnWidth = (getWidth() - headerWidth) / mColumns; rulerView.layout(0, 0, getWidth(), getHeight()); final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) continue; if (child instanceof BlockView) { final BlockView blockView = (BlockView) child; final int top = rulerView.getTimeVerticalOffset(blockView.getStartTime()); final int bottom = rulerView.getTimeVerticalOffset(blockView.getEndTime()); final int left = headerWidth + (blockView.getColumn() * columnWidth); final int right = left + columnWidth; child.layout(left, top, right, bottom); } } // Align now view to match current time final View nowView = mNowView; final long now = UIUtils.getCurrentTime(getContext()); final int top = rulerView.getTimeVerticalOffset(now); final int bottom = top + nowView.getMeasuredHeight(); final int left = 0; final int right = getWidth(); nowView.layout(left, top, right, bottom); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.Vendors; import com.google.android.apps.iosched.ui.phone.SessionDetailActivity; import com.google.android.apps.iosched.ui.phone.VendorDetailActivity; import android.app.SearchManager; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.TabHost; import android.widget.TabWidget; import android.widget.TextView; /** * An activity that shows session and sandbox search results. This activity can be either single * or multi-pane, depending on the device configuration. We want the multi-pane support that * {@link BaseMultiPaneActivity} offers, so we inherit from it instead of * {@link BaseSinglePaneActivity}. */ public class SearchActivity extends BaseMultiPaneActivity { public static final String TAG_SESSIONS = "sessions"; public static final String TAG_VENDORS = "vendors"; private String mQuery; private TabHost mTabHost; private TabWidget mTabWidget; private SessionsFragment mSessionsFragment; private VendorsFragment mVendorsFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); mQuery = intent.getStringExtra(SearchManager.QUERY); setContentView(R.layout.activity_search); getActivityHelper().setupActionBar(getTitle(), 0); final CharSequence title = getString(R.string.title_search_query, mQuery); getActivityHelper().setActionBarTitle(title); mTabHost = (TabHost) findViewById(android.R.id.tabhost); mTabWidget = (TabWidget) findViewById(android.R.id.tabs); mTabHost.setup(); setupSessionsTab(); setupVendorsTab(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); ViewGroup detailContainer = (ViewGroup) findViewById(R.id.fragment_container_search_detail); if (detailContainer != null && detailContainer.getChildCount() > 1) { findViewById(android.R.id.empty).setVisibility(View.GONE); } } @Override public void onNewIntent(Intent intent) { setIntent(intent); mQuery = intent.getStringExtra(SearchManager.QUERY); final CharSequence title = getString(R.string.title_search_query, mQuery); getActivityHelper().setActionBarTitle(title); mTabHost.setCurrentTab(0); mSessionsFragment.reloadFromArguments(getSessionsFragmentArguments()); mVendorsFragment.reloadFromArguments(getVendorsFragmentArguments()); } /** * Build and add "sessions" tab. */ private void setupSessionsTab() { // TODO: this is very inefficient and messy, clean it up FrameLayout fragmentContainer = new FrameLayout(this); fragmentContainer.setId(R.id.fragment_sessions); fragmentContainer.setLayoutParams( new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); ((ViewGroup) findViewById(android.R.id.tabcontent)).addView(fragmentContainer); final FragmentManager fm = getSupportFragmentManager(); mSessionsFragment = (SessionsFragment) fm.findFragmentByTag("sessions"); if (mSessionsFragment == null) { mSessionsFragment = new SessionsFragment(); mSessionsFragment.setArguments(getSessionsFragmentArguments()); fm.beginTransaction() .add(R.id.fragment_sessions, mSessionsFragment, "sessions") .commit(); } else { mSessionsFragment.reloadFromArguments(getSessionsFragmentArguments()); } // Sessions content comes from reused activity mTabHost.addTab(mTabHost.newTabSpec(TAG_SESSIONS) .setIndicator(buildIndicator(R.string.starred_sessions)) .setContent(R.id.fragment_sessions)); } /** * Build and add "vendors" tab. */ private void setupVendorsTab() { // TODO: this is very inefficient and messy, clean it up FrameLayout fragmentContainer = new FrameLayout(this); fragmentContainer.setId(R.id.fragment_vendors); fragmentContainer.setLayoutParams( new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); ((ViewGroup) findViewById(android.R.id.tabcontent)).addView(fragmentContainer); final FragmentManager fm = getSupportFragmentManager(); mVendorsFragment = (VendorsFragment) fm.findFragmentByTag("vendors"); if (mVendorsFragment == null) { mVendorsFragment = new VendorsFragment(); mVendorsFragment.setArguments(getVendorsFragmentArguments()); fm.beginTransaction() .add(R.id.fragment_vendors, mVendorsFragment, "vendors") .commit(); } else { mVendorsFragment.reloadFromArguments(getVendorsFragmentArguments()); } // Vendors content comes from reused activity mTabHost.addTab(mTabHost.newTabSpec(TAG_VENDORS) .setIndicator(buildIndicator(R.string.starred_vendors)) .setContent(R.id.fragment_vendors)); } private Bundle getSessionsFragmentArguments() { return intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, Sessions.buildSearchUri(mQuery))); } private Bundle getVendorsFragmentArguments() { return intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, Vendors.buildSearchUri(mQuery))); } /** * Build a {@link View} to be used as a tab indicator, setting the requested string resource as * its label. */ private View buildIndicator(int textRes) { final TextView indicator = (TextView) getLayoutInflater().inflate(R.layout.tab_indicator, mTabWidget, false); indicator.setText(textRes); return indicator; } @Override public BaseMultiPaneActivity.FragmentReplaceInfo onSubstituteFragmentForActivityLaunch( String activityClassName) { if (findViewById(R.id.fragment_container_search_detail) != null) { // The layout we currently have has a detail container, we can add fragments there. findViewById(android.R.id.empty).setVisibility(View.GONE); if (SessionDetailActivity.class.getName().equals(activityClassName)) { clearSelectedItems(); return new BaseMultiPaneActivity.FragmentReplaceInfo( SessionDetailFragment.class, "session_detail", R.id.fragment_container_search_detail); } else if (VendorDetailActivity.class.getName().equals(activityClassName)) { clearSelectedItems(); return new BaseMultiPaneActivity.FragmentReplaceInfo( VendorDetailFragment.class, "vendor_detail", R.id.fragment_container_search_detail); } } return null; } private void clearSelectedItems() { if (mSessionsFragment != null) { mSessionsFragment.clearCheckedPosition(); } if (mVendorsFragment != null) { mVendorsFragment.clearCheckedPosition(); } } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import android.os.Bundle; import android.support.v4.app.Fragment; public class BulletinActivity extends BaseSinglePaneActivity { @Override protected Fragment onCreatePane() { return new BulletinFragment(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; /** * A {@link BaseActivity} that simply contains a single fragment. The intent used to invoke this * activity is forwarded to the fragment as arguments during fragment instantiation. Derived * activities should only need to implement * {@link com.google.android.apps.iosched.ui.BaseSinglePaneActivity#onCreatePane()}. */ public abstract class BaseSinglePaneActivity extends BaseActivity { private Fragment mFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_singlepane_empty); getActivityHelper().setupActionBar(getTitle(), 0); final String customTitle = getIntent().getStringExtra(Intent.EXTRA_TITLE); getActivityHelper().setActionBarTitle(customTitle != null ? customTitle : getTitle()); if (savedInstanceState == null) { mFragment = onCreatePane(); mFragment.setArguments(intentToFragmentArguments(getIntent())); getSupportFragmentManager().beginTransaction() .add(R.id.root_container, mFragment) .commit(); } } /** * Called in <code>onCreate</code> when the fragment constituting this activity is needed. * The returned fragment's arguments will be set to the intent used to invoke this activity. */ protected abstract Fragment onCreatePane(); }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Rooms; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.ParserUtils; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.support.v4.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.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; /** * Shows a {@link WebView} with a map of the conference venue. */ public class MapFragment extends Fragment { private static final String TAG = "MapFragment"; /** * When specified, will automatically point the map to the requested room. */ public static final String EXTRA_ROOM = "com.google.android.iosched.extra.ROOM"; private static final String MAP_JSI_NAME = "MAP_CONTAINER"; private static final String MAP_URL = "http://www.google.com/events/io/2011/embed.html"; private static boolean CLEAR_CACHE_ON_LOAD = false; private WebView mWebView; private View mLoadingSpinner; private boolean mMapInitialized = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); AnalyticsUtils.getInstance(getActivity()).trackPageView("/Map"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_webview_with_spinner, null); // For some reason, if we omit this, NoSaveStateFrameLayout thinks we are // FILL_PARENT / WRAP_CONTENT, making the progress bar stick to the top of the activity. root.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); mLoadingSpinner = root.findViewById(R.id.loading_spinner); mWebView = (WebView) root.findViewById(R.id.webview); mWebView.setWebChromeClient(mWebChromeClient); mWebView.setWebViewClient(mWebViewClient); mWebView.post(new Runnable() { public void run() { // Initialize web view if (CLEAR_CACHE_ON_LOAD) { mWebView.clearCache(true); } mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false); mWebView.loadUrl(MAP_URL); mWebView.addJavascriptInterface(mMapJsiImpl, MAP_JSI_NAME); } }); return root; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.refresh_menu_items, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_refresh) { mWebView.reload(); return true; } return super.onOptionsItemSelected(item); } private void runJs(String js) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Loading javascript:" + js); } mWebView.loadUrl("javascript:" + js); } /** * Helper method to escape JavaScript strings. Useful when passing strings to a WebView via * "javascript:" calls. */ private static String escapeJsString(String s) { if (s == null) { return ""; } return s.replace("'", "\\'").replace("\"", "\\\""); } public void panLeft(float screenFraction) { runJs("IoMap.panLeft('" + screenFraction + "');"); } /** * I/O Conference Map JavaScript interface. */ private interface MapJsi { void openContentInfo(String test); void onMapReady(); } private WebChromeClient mWebChromeClient = new WebChromeClient() { public void onConsoleMessage(String message, int lineNumber, String sourceID) { Log.i(TAG, "JS Console message: (" + sourceID + ": " + lineNumber + ") " + message); } }; private WebViewClient mWebViewClient = new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); mLoadingSpinner.setVisibility(View.VISIBLE); mWebView.setVisibility(View.INVISIBLE); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); mLoadingSpinner.setVisibility(View.GONE); mWebView.setVisibility(View.VISIBLE); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { Log.e(TAG, "Error " + errorCode + ": " + description); Toast.makeText(view.getContext(), "Error " + errorCode + ": " + description, Toast.LENGTH_LONG).show(); super.onReceivedError(view, errorCode, description, failingUrl); } }; private MapJsi mMapJsiImpl = new MapJsi() { public void openContentInfo(String roomId) { final String possibleTrackId = ParserUtils.translateTrackIdAlias(roomId); final Intent intent; if (ParserUtils.LOCAL_TRACK_IDS.contains(possibleTrackId)) { // This is a track; open up the sandbox for the track, since room IDs that are // track IDs are sandbox areas in the map. Uri trackVendorsUri = ScheduleContract.Tracks.buildVendorsUri(possibleTrackId); intent = new Intent(Intent.ACTION_VIEW, trackVendorsUri); } else { Uri roomUri = Rooms.buildSessionsDirUri(roomId); intent = new Intent(Intent.ACTION_VIEW, roomUri); } getActivity().runOnUiThread(new Runnable() { public void run() { ((BaseActivity) getActivity()).openActivityOrFragment(intent); } }); } public void onMapReady() { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "onMapReady"); } final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); String showRoomId = null; if (!mMapInitialized && intent.hasExtra(EXTRA_ROOM)) { showRoomId = intent.getStringExtra(EXTRA_ROOM); } if (showRoomId != null) { runJs("IoMap.showLocationById('" + escapeJsString(showRoomId) + "');"); } mMapInitialized = true; } }; }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.provider; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.provider.ScheduleContract.Rooms; import com.google.android.apps.iosched.provider.ScheduleContract.SearchSuggest; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.Speakers; import com.google.android.apps.iosched.provider.ScheduleContract.Tracks; import com.google.android.apps.iosched.provider.ScheduleContract.Vendors; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSearchColumns; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSpeakers; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsTracks; import com.google.android.apps.iosched.provider.ScheduleDatabase.Tables; import com.google.android.apps.iosched.provider.ScheduleDatabase.VendorsSearchColumns; import com.google.android.apps.iosched.service.SyncService; import com.google.android.apps.iosched.util.SelectionBuilder; import android.app.Activity; import android.app.SearchManager; import android.content.ContentProvider; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentValues; import android.content.Context; import android.content.OperationApplicationException; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.ParcelFileDescriptor; import android.provider.BaseColumns; import android.util.Log; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Provider that stores {@link ScheduleContract} data. Data is usually inserted * by {@link SyncService}, and queried by various {@link Activity} instances. */ public class ScheduleProvider extends ContentProvider { private static final String TAG = "ScheduleProvider"; private static final boolean LOGV = Log.isLoggable(TAG, Log.VERBOSE); private ScheduleDatabase mOpenHelper; private static final UriMatcher sUriMatcher = buildUriMatcher(); private static final int BLOCKS = 100; private static final int BLOCKS_BETWEEN = 101; private static final int BLOCKS_ID = 102; private static final int BLOCKS_ID_SESSIONS = 103; private static final int TRACKS = 200; private static final int TRACKS_ID = 201; private static final int TRACKS_ID_SESSIONS = 202; private static final int TRACKS_ID_VENDORS = 203; private static final int ROOMS = 300; private static final int ROOMS_ID = 301; private static final int ROOMS_ID_SESSIONS = 302; private static final int SESSIONS = 400; private static final int SESSIONS_STARRED = 401; private static final int SESSIONS_SEARCH = 402; private static final int SESSIONS_AT = 403; private static final int SESSIONS_ID = 404; private static final int SESSIONS_ID_SPEAKERS = 405; private static final int SESSIONS_ID_TRACKS = 406; private static final int SPEAKERS = 500; private static final int SPEAKERS_ID = 501; private static final int SPEAKERS_ID_SESSIONS = 502; private static final int VENDORS = 600; private static final int VENDORS_STARRED = 601; private static final int VENDORS_SEARCH = 603; private static final int VENDORS_ID = 604; private static final int SEARCH_SUGGEST = 800; private static final String MIME_XML = "text/xml"; /** * Build and return a {@link UriMatcher} that catches all {@link Uri} * variations supported by this {@link ContentProvider}. */ private static UriMatcher buildUriMatcher() { final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); final String authority = ScheduleContract.CONTENT_AUTHORITY; matcher.addURI(authority, "blocks", BLOCKS); matcher.addURI(authority, "blocks/between/*/*", BLOCKS_BETWEEN); matcher.addURI(authority, "blocks/*", BLOCKS_ID); matcher.addURI(authority, "blocks/*/sessions", BLOCKS_ID_SESSIONS); matcher.addURI(authority, "tracks", TRACKS); matcher.addURI(authority, "tracks/*", TRACKS_ID); matcher.addURI(authority, "tracks/*/sessions", TRACKS_ID_SESSIONS); matcher.addURI(authority, "tracks/*/vendors", TRACKS_ID_VENDORS); matcher.addURI(authority, "rooms", ROOMS); matcher.addURI(authority, "rooms/*", ROOMS_ID); matcher.addURI(authority, "rooms/*/sessions", ROOMS_ID_SESSIONS); matcher.addURI(authority, "sessions", SESSIONS); matcher.addURI(authority, "sessions/starred", SESSIONS_STARRED); matcher.addURI(authority, "sessions/search/*", SESSIONS_SEARCH); matcher.addURI(authority, "sessions/at/*", SESSIONS_AT); matcher.addURI(authority, "sessions/*", SESSIONS_ID); matcher.addURI(authority, "sessions/*/speakers", SESSIONS_ID_SPEAKERS); matcher.addURI(authority, "sessions/*/tracks", SESSIONS_ID_TRACKS); matcher.addURI(authority, "speakers", SPEAKERS); matcher.addURI(authority, "speakers/*", SPEAKERS_ID); matcher.addURI(authority, "speakers/*/sessions", SPEAKERS_ID_SESSIONS); matcher.addURI(authority, "vendors", VENDORS); matcher.addURI(authority, "vendors/starred", VENDORS_STARRED); matcher.addURI(authority, "vendors/search/*", VENDORS_SEARCH); matcher.addURI(authority, "vendors/*", VENDORS_ID); matcher.addURI(authority, "search_suggest_query", SEARCH_SUGGEST); return matcher; } @Override public boolean onCreate() { final Context context = getContext(); mOpenHelper = new ScheduleDatabase(context); return true; } /** {@inheritDoc} */ @Override public String getType(Uri uri) { final int match = sUriMatcher.match(uri); switch (match) { case BLOCKS: return Blocks.CONTENT_TYPE; case BLOCKS_BETWEEN: return Blocks.CONTENT_TYPE; case BLOCKS_ID: return Blocks.CONTENT_ITEM_TYPE; case BLOCKS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case TRACKS: return Tracks.CONTENT_TYPE; case TRACKS_ID: return Tracks.CONTENT_ITEM_TYPE; case TRACKS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case TRACKS_ID_VENDORS: return Vendors.CONTENT_TYPE; case ROOMS: return Rooms.CONTENT_TYPE; case ROOMS_ID: return Rooms.CONTENT_ITEM_TYPE; case ROOMS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case SESSIONS: return Sessions.CONTENT_TYPE; case SESSIONS_STARRED: return Sessions.CONTENT_TYPE; case SESSIONS_SEARCH: return Sessions.CONTENT_TYPE; case SESSIONS_AT: return Sessions.CONTENT_TYPE; case SESSIONS_ID: return Sessions.CONTENT_ITEM_TYPE; case SESSIONS_ID_SPEAKERS: return Speakers.CONTENT_TYPE; case SESSIONS_ID_TRACKS: return Tracks.CONTENT_TYPE; case SPEAKERS: return Speakers.CONTENT_TYPE; case SPEAKERS_ID: return Speakers.CONTENT_ITEM_TYPE; case SPEAKERS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case VENDORS: return Vendors.CONTENT_TYPE; case VENDORS_STARRED: return Vendors.CONTENT_TYPE; case VENDORS_SEARCH: return Vendors.CONTENT_TYPE; case VENDORS_ID: return Vendors.CONTENT_ITEM_TYPE; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } } /** {@inheritDoc} */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { if (LOGV) Log.v(TAG, "query(uri=" + uri + ", proj=" + Arrays.toString(projection) + ")"); final SQLiteDatabase db = mOpenHelper.getReadableDatabase(); final int match = sUriMatcher.match(uri); switch (match) { default: { // Most cases are handled with simple SelectionBuilder final SelectionBuilder builder = buildExpandedSelection(uri, match); return builder.where(selection, selectionArgs).query(db, projection, sortOrder); } case SEARCH_SUGGEST: { final SelectionBuilder builder = new SelectionBuilder(); // Adjust incoming query to become SQL text match selectionArgs[0] = selectionArgs[0] + "%"; builder.table(Tables.SEARCH_SUGGEST); builder.where(selection, selectionArgs); builder.map(SearchManager.SUGGEST_COLUMN_QUERY, SearchManager.SUGGEST_COLUMN_TEXT_1); projection = new String[] { BaseColumns._ID, SearchManager.SUGGEST_COLUMN_TEXT_1, SearchManager.SUGGEST_COLUMN_QUERY }; final String limit = uri.getQueryParameter(SearchManager.SUGGEST_PARAMETER_LIMIT); return builder.query(db, projection, null, null, SearchSuggest.DEFAULT_SORT, limit); } } } /** {@inheritDoc} */ @Override public Uri insert(Uri uri, ContentValues values) { if (LOGV) Log.v(TAG, "insert(uri=" + uri + ", values=" + values.toString() + ")"); final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); switch (match) { case BLOCKS: { db.insertOrThrow(Tables.BLOCKS, null, values); getContext().getContentResolver().notifyChange(uri, null); return Blocks.buildBlockUri(values.getAsString(Blocks.BLOCK_ID)); } case TRACKS: { db.insertOrThrow(Tables.TRACKS, null, values); getContext().getContentResolver().notifyChange(uri, null); return Tracks.buildTrackUri(values.getAsString(Tracks.TRACK_ID)); } case ROOMS: { db.insertOrThrow(Tables.ROOMS, null, values); getContext().getContentResolver().notifyChange(uri, null); return Rooms.buildRoomUri(values.getAsString(Rooms.ROOM_ID)); } case SESSIONS: { db.insertOrThrow(Tables.SESSIONS, null, values); getContext().getContentResolver().notifyChange(uri, null); return Sessions.buildSessionUri(values.getAsString(Sessions.SESSION_ID)); } case SESSIONS_ID_SPEAKERS: { db.insertOrThrow(Tables.SESSIONS_SPEAKERS, null, values); getContext().getContentResolver().notifyChange(uri, null); return Speakers.buildSpeakerUri(values.getAsString(SessionsSpeakers.SPEAKER_ID)); } case SESSIONS_ID_TRACKS: { db.insertOrThrow(Tables.SESSIONS_TRACKS, null, values); getContext().getContentResolver().notifyChange(uri, null); return Tracks.buildTrackUri(values.getAsString(SessionsTracks.TRACK_ID)); } case SPEAKERS: { db.insertOrThrow(Tables.SPEAKERS, null, values); getContext().getContentResolver().notifyChange(uri, null); return Speakers.buildSpeakerUri(values.getAsString(Speakers.SPEAKER_ID)); } case VENDORS: { db.insertOrThrow(Tables.VENDORS, null, values); getContext().getContentResolver().notifyChange(uri, null); return Vendors.buildVendorUri(values.getAsString(Vendors.VENDOR_ID)); } case SEARCH_SUGGEST: { db.insertOrThrow(Tables.SEARCH_SUGGEST, null, values); getContext().getContentResolver().notifyChange(uri, null); return SearchSuggest.CONTENT_URI; } default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } /** {@inheritDoc} */ @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { if (LOGV) Log.v(TAG, "update(uri=" + uri + ", values=" + values.toString() + ")"); final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final SelectionBuilder builder = buildSimpleSelection(uri); int retVal = builder.where(selection, selectionArgs).update(db, values); getContext().getContentResolver().notifyChange(uri, null); return retVal; } /** {@inheritDoc} */ @Override public int delete(Uri uri, String selection, String[] selectionArgs) { if (LOGV) Log.v(TAG, "delete(uri=" + uri + ")"); final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final SelectionBuilder builder = buildSimpleSelection(uri); int retVal = builder.where(selection, selectionArgs).delete(db); getContext().getContentResolver().notifyChange(uri, null); return retVal; } /** * Apply the given set of {@link ContentProviderOperation}, executing inside * a {@link SQLiteDatabase} transaction. All changes will be rolled back if * any single one fails. */ @Override public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) throws OperationApplicationException { final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); db.beginTransaction(); try { final int numOperations = operations.size(); final ContentProviderResult[] results = new ContentProviderResult[numOperations]; for (int i = 0; i < numOperations; i++) { results[i] = operations.get(i).apply(this, results, i); } db.setTransactionSuccessful(); return results; } finally { db.endTransaction(); } } /** * Build a simple {@link SelectionBuilder} to match the requested * {@link Uri}. This is usually enough to support {@link #insert}, * {@link #update}, and {@link #delete} operations. */ private SelectionBuilder buildSimpleSelection(Uri uri) { final SelectionBuilder builder = new SelectionBuilder(); final int match = sUriMatcher.match(uri); switch (match) { case BLOCKS: { return builder.table(Tables.BLOCKS); } case BLOCKS_ID: { final String blockId = Blocks.getBlockId(uri); return builder.table(Tables.BLOCKS) .where(Blocks.BLOCK_ID + "=?", blockId); } case TRACKS: { return builder.table(Tables.TRACKS); } case TRACKS_ID: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.TRACKS) .where(Tracks.TRACK_ID + "=?", trackId); } case ROOMS: { return builder.table(Tables.ROOMS); } case ROOMS_ID: { final String roomId = Rooms.getRoomId(uri); return builder.table(Tables.ROOMS) .where(Rooms.ROOM_ID + "=?", roomId); } case SESSIONS: { return builder.table(Tables.SESSIONS); } case SESSIONS_ID: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS) .where(Sessions.SESSION_ID + "=?", sessionId); } case SESSIONS_ID_SPEAKERS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_SPEAKERS) .where(Sessions.SESSION_ID + "=?", sessionId); } case SESSIONS_ID_TRACKS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_TRACKS) .where(Sessions.SESSION_ID + "=?", sessionId); } case SPEAKERS: { return builder.table(Tables.SPEAKERS); } case SPEAKERS_ID: { final String speakerId = Speakers.getSpeakerId(uri); return builder.table(Tables.SPEAKERS) .where(Speakers.SPEAKER_ID + "=?", speakerId); } case VENDORS: { return builder.table(Tables.VENDORS); } case VENDORS_ID: { final String vendorId = Vendors.getVendorId(uri); return builder.table(Tables.VENDORS) .where(Vendors.VENDOR_ID + "=?", vendorId); } case SEARCH_SUGGEST: { return builder.table(Tables.SEARCH_SUGGEST); } default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } /** * Build an advanced {@link SelectionBuilder} to match the requested * {@link Uri}. This is usually only used by {@link #query}, since it * performs table joins useful for {@link Cursor} data. */ private SelectionBuilder buildExpandedSelection(Uri uri, int match) { final SelectionBuilder builder = new SelectionBuilder(); switch (match) { case BLOCKS: { return builder.table(Tables.BLOCKS); } case BLOCKS_BETWEEN: { final List<String> segments = uri.getPathSegments(); final String startTime = segments.get(2); final String endTime = segments.get(3); return builder.table(Tables.BLOCKS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.CONTAINS_STARRED, Subquery.BLOCK_CONTAINS_STARRED) .where(Blocks.BLOCK_START + ">=?", startTime) .where(Blocks.BLOCK_START + "<=?", endTime); } case BLOCKS_ID: { final String blockId = Blocks.getBlockId(uri); return builder.table(Tables.BLOCKS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.CONTAINS_STARRED, Subquery.BLOCK_CONTAINS_STARRED) .where(Blocks.BLOCK_ID + "=?", blockId); } case BLOCKS_ID_SESSIONS: { final String blockId = Blocks.getBlockId(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.CONTAINS_STARRED, Subquery.BLOCK_CONTAINS_STARRED) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_BLOCK_ID + "=?", blockId); } case TRACKS: { return builder.table(Tables.TRACKS) .map(Tracks.SESSIONS_COUNT, Subquery.TRACK_SESSIONS_COUNT) .map(Tracks.VENDORS_COUNT, Subquery.TRACK_VENDORS_COUNT); } case TRACKS_ID: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.TRACKS) .where(Tracks.TRACK_ID + "=?", trackId); } case TRACKS_ID_SESSIONS: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.SESSIONS_TRACKS_JOIN_SESSIONS_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_TRACKS_TRACK_ID + "=?", trackId); } case TRACKS_ID_VENDORS: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS) .where(Qualified.VENDORS_TRACK_ID + "=?", trackId); } case ROOMS: { return builder.table(Tables.ROOMS); } case ROOMS_ID: { final String roomId = Rooms.getRoomId(uri); return builder.table(Tables.ROOMS) .where(Rooms.ROOM_ID + "=?", roomId); } case ROOMS_ID_SESSIONS: { final String roomId = Rooms.getRoomId(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_ROOM_ID + "=?", roomId); } case SESSIONS: { return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS); } case SESSIONS_STARRED: { return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Sessions.SESSION_STARRED + "=1"); } case SESSIONS_SEARCH: { final String query = Sessions.getSearchQuery(uri); return builder.table(Tables.SESSIONS_SEARCH_JOIN_SESSIONS_BLOCKS_ROOMS) .map(Sessions.SEARCH_SNIPPET, Subquery.SESSIONS_SNIPPET) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(SessionsSearchColumns.BODY + " MATCH ?", query); } case SESSIONS_AT: { final List<String> segments = uri.getPathSegments(); final String time = segments.get(2); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Sessions.BLOCK_START + "<=?", time) .where(Sessions.BLOCK_END + ">=?", time); } case SESSIONS_ID: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_SESSION_ID + "=?", sessionId); } case SESSIONS_ID_SPEAKERS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_SPEAKERS_JOIN_SPEAKERS) .mapToTable(Speakers._ID, Tables.SPEAKERS) .mapToTable(Speakers.SPEAKER_ID, Tables.SPEAKERS) .where(Qualified.SESSIONS_SPEAKERS_SESSION_ID + "=?", sessionId); } case SESSIONS_ID_TRACKS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_TRACKS_JOIN_TRACKS) .mapToTable(Tracks._ID, Tables.TRACKS) .mapToTable(Tracks.TRACK_ID, Tables.TRACKS) .where(Qualified.SESSIONS_TRACKS_SESSION_ID + "=?", sessionId); } case SPEAKERS: { return builder.table(Tables.SPEAKERS); } case SPEAKERS_ID: { final String speakerId = Speakers.getSpeakerId(uri); return builder.table(Tables.SPEAKERS) .where(Speakers.SPEAKER_ID + "=?", speakerId); } case SPEAKERS_ID_SESSIONS: { final String speakerId = Speakers.getSpeakerId(uri); return builder.table(Tables.SESSIONS_SPEAKERS_JOIN_SESSIONS_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_SPEAKERS_SPEAKER_ID + "=?", speakerId); } case VENDORS: { return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS); } case VENDORS_STARRED: { return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS) .where(Vendors.VENDOR_STARRED + "=1"); } case VENDORS_SEARCH: { final String query = Vendors.getSearchQuery(uri); return builder.table(Tables.VENDORS_SEARCH_JOIN_VENDORS_TRACKS) .map(Vendors.SEARCH_SNIPPET, Subquery.VENDORS_SNIPPET) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.VENDOR_ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS) .where(VendorsSearchColumns.BODY + " MATCH ?", query); } case VENDORS_ID: { final String vendorId = Vendors.getVendorId(uri); return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS) .where(Vendors.VENDOR_ID + "=?", vendorId); } default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { final int match = sUriMatcher.match(uri); switch (match) { default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } private interface Subquery { String BLOCK_SESSIONS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_SESSION_ID + ") FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + ")"; String BLOCK_CONTAINS_STARRED = "(SELECT MAX(" + Qualified.SESSIONS_STARRED + ") FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + ")"; String TRACK_SESSIONS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_TRACKS_SESSION_ID + ") FROM " + Tables.SESSIONS_TRACKS + " WHERE " + Qualified.SESSIONS_TRACKS_TRACK_ID + "=" + Qualified.TRACKS_TRACK_ID + ")"; String TRACK_VENDORS_COUNT = "(SELECT COUNT(" + Qualified.VENDORS_VENDOR_ID + ") FROM " + Tables.VENDORS + " WHERE " + Qualified.VENDORS_TRACK_ID + "=" + Qualified.TRACKS_TRACK_ID + ")"; String SESSIONS_SNIPPET = "snippet(" + Tables.SESSIONS_SEARCH + ",'{','}','\u2026')"; String VENDORS_SNIPPET = "snippet(" + Tables.VENDORS_SEARCH + ",'{','}','\u2026')"; } /** * {@link ScheduleContract} fields that are fully qualified with a specific * parent {@link Tables}. Used when needed to work around SQL ambiguity. */ private interface Qualified { String SESSIONS_SESSION_ID = Tables.SESSIONS + "." + Sessions.SESSION_ID; String SESSIONS_BLOCK_ID = Tables.SESSIONS + "." + Sessions.BLOCK_ID; String SESSIONS_ROOM_ID = Tables.SESSIONS + "." + Sessions.ROOM_ID; String SESSIONS_TRACKS_SESSION_ID = Tables.SESSIONS_TRACKS + "." + SessionsTracks.SESSION_ID; String SESSIONS_TRACKS_TRACK_ID = Tables.SESSIONS_TRACKS + "." + SessionsTracks.TRACK_ID; String SESSIONS_SPEAKERS_SESSION_ID = Tables.SESSIONS_SPEAKERS + "." + SessionsSpeakers.SESSION_ID; String SESSIONS_SPEAKERS_SPEAKER_ID = Tables.SESSIONS_SPEAKERS + "." + SessionsSpeakers.SPEAKER_ID; String VENDORS_VENDOR_ID = Tables.VENDORS + "." + Vendors.VENDOR_ID; String VENDORS_TRACK_ID = Tables.VENDORS + "." + Vendors.TRACK_ID; @SuppressWarnings("hiding") String SESSIONS_STARRED = Tables.SESSIONS + "." + Sessions.SESSION_STARRED; String TRACKS_TRACK_ID = Tables.TRACKS + "." + Tracks.TRACK_ID; String BLOCKS_BLOCK_ID = Tables.BLOCKS + "." + Blocks.BLOCK_ID; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.provider; import com.google.android.apps.iosched.util.ParserUtils; import android.app.SearchManager; import android.graphics.Color; import android.net.Uri; import android.provider.BaseColumns; import android.text.format.DateUtils; import java.util.List; /** * Contract class for interacting with {@link ScheduleProvider}. Unless * otherwise noted, all time-based fields are milliseconds since epoch and can * be compared against {@link System#currentTimeMillis()}. * <p> * The backing {@link android.content.ContentProvider} assumes that {@link Uri} are generated * using stronger {@link String} identifiers, instead of {@code int} * {@link BaseColumns#_ID} values, which are prone to shuffle during sync. */ public class ScheduleContract { /** * Special value for {@link SyncColumns#UPDATED} indicating that an entry * has never been updated, or doesn't exist yet. */ public static final long UPDATED_NEVER = -2; /** * Special value for {@link SyncColumns#UPDATED} indicating that the last * update time is unknown, usually when inserted from a local file source. */ public static final long UPDATED_UNKNOWN = -1; public interface SyncColumns { /** Last time this entry was updated or synchronized. */ String UPDATED = "updated"; } interface BlocksColumns { /** Unique string identifying this block of time. */ String BLOCK_ID = "block_id"; /** Title describing this block of time. */ String BLOCK_TITLE = "block_title"; /** Time when this block starts. */ String BLOCK_START = "block_start"; /** Time when this block ends. */ String BLOCK_END = "block_end"; /** Type describing this block. */ String BLOCK_TYPE = "block_type"; } interface TracksColumns { /** Unique string identifying this track. */ String TRACK_ID = "track_id"; /** Name describing this track. */ String TRACK_NAME = "track_name"; /** Color used to identify this track, in {@link Color#argb} format. */ String TRACK_COLOR = "track_color"; /** Body of text explaining this track in detail. */ String TRACK_ABSTRACT = "track_abstract"; } interface RoomsColumns { /** Unique string identifying this room. */ String ROOM_ID = "room_id"; /** Name describing this room. */ String ROOM_NAME = "room_name"; /** Building floor this room exists on. */ String ROOM_FLOOR = "room_floor"; } interface SessionsColumns { /** Unique string identifying this session. */ String SESSION_ID = "session_id"; /** Difficulty level of the session. */ String SESSION_LEVEL = "session_level"; /** Title describing this track. */ String SESSION_TITLE = "session_title"; /** Body of text explaining this session in detail. */ String SESSION_ABSTRACT = "session_abstract"; /** Requirements that attendees should meet. */ String SESSION_REQUIREMENTS = "session_requirements"; /** Kewords/tags for this session. */ String SESSION_KEYWORDS = "session_keywords"; /** Hashtag for this session. */ String SESSION_HASHTAG = "session_hashtag"; /** Slug (short name) for this session. */ String SESSION_SLUG = "session_slug"; /** Full URL to session online. */ String SESSION_URL = "session_url"; /** Link to Moderator for this session. */ String SESSION_MODERATOR_URL = "session_moderator_url"; /** Full URL to YouTube. */ String SESSION_YOUTUBE_URL = "session_youtube_url"; /** Full URL to PDF. */ String SESSION_PDF_URL = "session_pdf_url"; /** Full URL to speakermeter/external feedback URL. */ String SESSION_FEEDBACK_URL = "session_feedback_url"; /** Full URL to official session notes. */ String SESSION_NOTES_URL = "session_notes_url"; /** User-specific flag indicating starred status. */ String SESSION_STARRED = "session_starred"; } interface SpeakersColumns { /** Unique string identifying this speaker. */ String SPEAKER_ID = "speaker_id"; /** Name of this speaker. */ String SPEAKER_NAME = "speaker_name"; /** Profile photo of this speaker. */ String SPEAKER_IMAGE_URL = "speaker_image_url"; /** Company this speaker works for. */ String SPEAKER_COMPANY = "speaker_company"; /** Body of text describing this speaker in detail. */ String SPEAKER_ABSTRACT = "speaker_abstract"; /** Full URL to the speaker's profile. */ String SPEAKER_URL = "speaker_url"; } interface VendorsColumns { /** Unique string identifying this vendor. */ String VENDOR_ID = "vendor_id"; /** Name of this vendor. */ String VENDOR_NAME = "vendor_name"; /** Location or city this vendor is based in. */ String VENDOR_LOCATION = "vendor_location"; /** Body of text describing this vendor. */ String VENDOR_DESC = "vendor_desc"; /** Link to vendor online. */ String VENDOR_URL = "vendor_url"; /** Body of text describing the product of this vendor. */ String VENDOR_PRODUCT_DESC = "vendor_product_desc"; /** Link to vendor logo. */ String VENDOR_LOGO_URL = "vendor_logo_url"; /** User-specific flag indicating starred status. */ String VENDOR_STARRED = "vendor_starred"; } public static final String CONTENT_AUTHORITY = "com.google.android.apps.iosched"; private static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY); private static final String PATH_BLOCKS = "blocks"; private static final String PATH_AT = "at"; private static final String PATH_BETWEEN = "between"; private static final String PATH_TRACKS = "tracks"; private static final String PATH_ROOMS = "rooms"; private static final String PATH_SESSIONS = "sessions"; private static final String PATH_STARRED = "starred"; private static final String PATH_SPEAKERS = "speakers"; private static final String PATH_VENDORS = "vendors"; private static final String PATH_EXPORT = "export"; private static final String PATH_SEARCH = "search"; private static final String PATH_SEARCH_SUGGEST = "search_suggest_query"; /** * Blocks are generic timeslots that {@link Sessions} and other related * events fall into. */ public static class Blocks implements BlocksColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_BLOCKS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.block"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.block"; /** Count of {@link Sessions} inside given block. */ public static final String SESSIONS_COUNT = "sessions_count"; /** * Flag indicating that at least one {@link Sessions#SESSION_ID} inside * this block has {@link Sessions#SESSION_STARRED} set. */ public static final String CONTAINS_STARRED = "contains_starred"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + " ASC, " + BlocksColumns.BLOCK_END + " ASC"; /** Build {@link Uri} for requested {@link #BLOCK_ID}. */ public static Uri buildBlockUri(String blockId) { return CONTENT_URI.buildUpon().appendPath(blockId).build(); } /** * Build {@link Uri} that references any {@link Sessions} associated * with the requested {@link #BLOCK_ID}. */ public static Uri buildSessionsUri(String blockId) { return CONTENT_URI.buildUpon().appendPath(blockId).appendPath(PATH_SESSIONS).build(); } /** * Build {@link Uri} that references any {@link Blocks} that occur * between the requested time boundaries. */ public static Uri buildBlocksBetweenDirUri(long startTime, long endTime) { return CONTENT_URI.buildUpon().appendPath(PATH_BETWEEN).appendPath( String.valueOf(startTime)).appendPath(String.valueOf(endTime)).build(); } /** Read {@link #BLOCK_ID} from {@link Blocks} {@link Uri}. */ public static String getBlockId(Uri uri) { return uri.getPathSegments().get(1); } /** * Generate a {@link #BLOCK_ID} that will always match the requested * {@link Blocks} details. */ public static String generateBlockId(long startTime, long endTime) { startTime /= DateUtils.SECOND_IN_MILLIS; endTime /= DateUtils.SECOND_IN_MILLIS; return ParserUtils.sanitizeId(startTime + "-" + endTime); } } /** * Tracks are overall categories for {@link Sessions} and {@link Vendors}, * such as "Android" or "Enterprise." */ public static class Tracks implements TracksColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_TRACKS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.track"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.track"; /** Count of {@link Sessions} inside given track. */ public static final String SESSIONS_COUNT = "sessions_count"; /** Count of {@link Vendors} inside given track. */ public static final String VENDORS_COUNT = "vendors_count"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = TracksColumns.TRACK_NAME + " ASC"; /** "All tracks" ID. */ public static final String ALL_TRACK_ID = "all"; /** Build {@link Uri} for requested {@link #TRACK_ID}. */ public static Uri buildTrackUri(String trackId) { return CONTENT_URI.buildUpon().appendPath(trackId).build(); } /** * Build {@link Uri} that references any {@link Sessions} associated * with the requested {@link #TRACK_ID}. */ public static Uri buildSessionsUri(String trackId) { return CONTENT_URI.buildUpon().appendPath(trackId).appendPath(PATH_SESSIONS).build(); } /** * Build {@link Uri} that references any {@link Vendors} associated with * the requested {@link #TRACK_ID}. */ public static Uri buildVendorsUri(String trackId) { return CONTENT_URI.buildUpon().appendPath(trackId).appendPath(PATH_VENDORS).build(); } /** Read {@link #TRACK_ID} from {@link Tracks} {@link Uri}. */ public static String getTrackId(Uri uri) { return uri.getPathSegments().get(1); } /** * Generate a {@link #TRACK_ID} that will always match the requested * {@link Tracks} details. */ public static String generateTrackId(String title) { return ParserUtils.sanitizeId(title); } } /** * Rooms are physical locations at the conference venue. */ public static class Rooms implements RoomsColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_ROOMS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.room"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.room"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = RoomsColumns.ROOM_FLOOR + " ASC, " + RoomsColumns.ROOM_NAME + " COLLATE NOCASE ASC"; /** Build {@link Uri} for requested {@link #ROOM_ID}. */ public static Uri buildRoomUri(String roomId) { return CONTENT_URI.buildUpon().appendPath(roomId).build(); } /** * Build {@link Uri} that references any {@link Sessions} associated * with the requested {@link #ROOM_ID}. */ public static Uri buildSessionsDirUri(String roomId) { return CONTENT_URI.buildUpon().appendPath(roomId).appendPath(PATH_SESSIONS).build(); } /** Read {@link #ROOM_ID} from {@link Rooms} {@link Uri}. */ public static String getRoomId(Uri uri) { return uri.getPathSegments().get(1); } /** * Generate a {@link #ROOM_ID} that will always match the requested * {@link Rooms} details. */ public static String generateRoomId(String room) { return ParserUtils.sanitizeId(room); } } /** * Each session is a block of time that has a {@link Tracks}, a * {@link Rooms}, and zero or more {@link Speakers}. */ public static class Sessions implements SessionsColumns, BlocksColumns, RoomsColumns, SyncColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_SESSIONS).build(); public static final Uri CONTENT_STARRED_URI = CONTENT_URI.buildUpon().appendPath(PATH_STARRED).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.session"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.session"; public static final String BLOCK_ID = "block_id"; public static final String ROOM_ID = "room_id"; public static final String SEARCH_SNIPPET = "search_snippet"; // TODO: shortcut primary track to offer sub-sorting here /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + " ASC," + SessionsColumns.SESSION_TITLE + " COLLATE NOCASE ASC"; /** Build {@link Uri} for requested {@link #SESSION_ID}. */ public static Uri buildSessionUri(String sessionId) { return CONTENT_URI.buildUpon().appendPath(sessionId).build(); } /** * Build {@link Uri} that references any {@link Speakers} associated * with the requested {@link #SESSION_ID}. */ public static Uri buildSpeakersDirUri(String sessionId) { return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_SPEAKERS).build(); } /** * Build {@link Uri} that references any {@link Tracks} associated with * the requested {@link #SESSION_ID}. */ public static Uri buildTracksDirUri(String sessionId) { return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_TRACKS).build(); } public static Uri buildSessionsAtDirUri(long time) { return CONTENT_URI.buildUpon().appendPath(PATH_AT).appendPath(String.valueOf(time)) .build(); } public static Uri buildSearchUri(String query) { return CONTENT_URI.buildUpon().appendPath(PATH_SEARCH).appendPath(query).build(); } public static boolean isSearchUri(Uri uri) { List<String> pathSegments = uri.getPathSegments(); return pathSegments.size() >= 2 && PATH_SEARCH.equals(pathSegments.get(1)); } /** Read {@link #SESSION_ID} from {@link Sessions} {@link Uri}. */ public static String getSessionId(Uri uri) { return uri.getPathSegments().get(1); } public static String getSearchQuery(Uri uri) { return uri.getPathSegments().get(2); } /** * Generate a {@link #SESSION_ID} that will always match the requested * {@link Sessions} details. */ public static String generateSessionId(String title) { return ParserUtils.sanitizeId(title); } } /** * Speakers are individual people that lead {@link Sessions}. */ public static class Speakers implements SpeakersColumns, SyncColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_SPEAKERS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.speaker"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.speaker"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = SpeakersColumns.SPEAKER_NAME + " COLLATE NOCASE ASC"; /** Build {@link Uri} for requested {@link #SPEAKER_ID}. */ public static Uri buildSpeakerUri(String speakerId) { return CONTENT_URI.buildUpon().appendPath(speakerId).build(); } /** * Build {@link Uri} that references any {@link Sessions} associated * with the requested {@link #SPEAKER_ID}. */ public static Uri buildSessionsDirUri(String speakerId) { return CONTENT_URI.buildUpon().appendPath(speakerId).appendPath(PATH_SESSIONS).build(); } /** Read {@link #SPEAKER_ID} from {@link Speakers} {@link Uri}. */ public static String getSpeakerId(Uri uri) { return uri.getPathSegments().get(1); } /** * Generate a {@link #SPEAKER_ID} that will always match the requested * {@link Speakers} details. */ public static String generateSpeakerId(String speakerLdap) { return ParserUtils.sanitizeId(speakerLdap); } } /** * Each vendor is a company appearing at the conference that may be * associated with a specific {@link Tracks}. */ public static class Vendors implements VendorsColumns, SyncColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_VENDORS).build(); public static final Uri CONTENT_STARRED_URI = CONTENT_URI.buildUpon().appendPath(PATH_STARRED).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.vendor"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.vendor"; /** {@link Tracks#TRACK_ID} that this vendor belongs to. */ public static final String TRACK_ID = "track_id"; public static final String SEARCH_SNIPPET = "search_snippet"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = VendorsColumns.VENDOR_NAME + " COLLATE NOCASE ASC"; /** Build {@link Uri} for requested {@link #VENDOR_ID}. */ public static Uri buildVendorUri(String vendorId) { return CONTENT_URI.buildUpon().appendPath(vendorId).build(); } public static Uri buildSearchUri(String query) { return CONTENT_URI.buildUpon().appendPath(PATH_SEARCH).appendPath(query).build(); } public static boolean isSearchUri(Uri uri) { List<String> pathSegments = uri.getPathSegments(); return pathSegments.size() >= 2 && PATH_SEARCH.equals(pathSegments.get(1)); } /** Read {@link #VENDOR_ID} from {@link Vendors} {@link Uri}. */ public static String getVendorId(Uri uri) { return uri.getPathSegments().get(1); } public static String getSearchQuery(Uri uri) { return uri.getPathSegments().get(2); } /** * Generate a {@link #VENDOR_ID} that will always match the requested * {@link Vendors} details. */ public static String generateVendorId(String companyLogo) { return ParserUtils.sanitizeId(companyLogo); } } public static class SearchSuggest { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_SEARCH_SUGGEST).build(); public static final String DEFAULT_SORT = SearchManager.SUGGEST_COLUMN_TEXT_1 + " COLLATE NOCASE ASC"; } private ScheduleContract() { } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.provider; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.provider.ScheduleContract.BlocksColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Rooms; import com.google.android.apps.iosched.provider.ScheduleContract.RoomsColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.SessionsColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Speakers; import com.google.android.apps.iosched.provider.ScheduleContract.SpeakersColumns; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Tracks; import com.google.android.apps.iosched.provider.ScheduleContract.TracksColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Vendors; import com.google.android.apps.iosched.provider.ScheduleContract.VendorsColumns; import android.app.SearchManager; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; import android.util.Log; /** * Helper for managing {@link SQLiteDatabase} that stores data for * {@link ScheduleProvider}. */ public class ScheduleDatabase extends SQLiteOpenHelper { private static final String TAG = "ScheduleDatabase"; private static final String DATABASE_NAME = "schedule.db"; // NOTE: carefully update onUpgrade() when bumping database versions to make // sure user data is saved. private static final int VER_LAUNCH = 21; private static final int VER_SESSION_FEEDBACK_URL = 22; private static final int VER_SESSION_NOTES_URL_SLUG = 23; private static final int DATABASE_VERSION = VER_SESSION_NOTES_URL_SLUG; interface Tables { String BLOCKS = "blocks"; String TRACKS = "tracks"; String ROOMS = "rooms"; String SESSIONS = "sessions"; String SPEAKERS = "speakers"; String SESSIONS_SPEAKERS = "sessions_speakers"; String SESSIONS_TRACKS = "sessions_tracks"; String VENDORS = "vendors"; String SESSIONS_SEARCH = "sessions_search"; String VENDORS_SEARCH = "vendors_search"; String SEARCH_SUGGEST = "search_suggest"; String SESSIONS_JOIN_BLOCKS_ROOMS = "sessions " + "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id " + "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id"; String VENDORS_JOIN_TRACKS = "vendors " + "LEFT OUTER JOIN tracks ON vendors.track_id=tracks.track_id"; String SESSIONS_SPEAKERS_JOIN_SPEAKERS = "sessions_speakers " + "LEFT OUTER JOIN speakers ON sessions_speakers.speaker_id=speakers.speaker_id"; String SESSIONS_SPEAKERS_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_speakers " + "LEFT OUTER JOIN sessions ON sessions_speakers.session_id=sessions.session_id " + "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id " + "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id"; String SESSIONS_TRACKS_JOIN_TRACKS = "sessions_tracks " + "LEFT OUTER JOIN tracks ON sessions_tracks.track_id=tracks.track_id"; String SESSIONS_TRACKS_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_tracks " + "LEFT OUTER JOIN sessions ON sessions_tracks.session_id=sessions.session_id " + "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id " + "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id"; String SESSIONS_SEARCH_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_search " + "LEFT OUTER JOIN sessions ON sessions_search.session_id=sessions.session_id " + "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id " + "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id"; String VENDORS_SEARCH_JOIN_VENDORS_TRACKS = "vendors_search " + "LEFT OUTER JOIN vendors ON vendors_search.vendor_id=vendors.vendor_id " + "LEFT OUTER JOIN tracks ON vendors.track_id=tracks.track_id"; } private interface Triggers { String SESSIONS_SEARCH_INSERT = "sessions_search_insert"; String SESSIONS_SEARCH_DELETE = "sessions_search_delete"; String SESSIONS_SEARCH_UPDATE = "sessions_search_update"; String VENDORS_SEARCH_INSERT = "vendors_search_insert"; String VENDORS_SEARCH_DELETE = "vendors_search_delete"; } public interface SessionsSpeakers { String SESSION_ID = "session_id"; String SPEAKER_ID = "speaker_id"; } public interface SessionsTracks { String SESSION_ID = "session_id"; String TRACK_ID = "track_id"; } interface SessionsSearchColumns { String SESSION_ID = "session_id"; String BODY = "body"; } interface VendorsSearchColumns { String VENDOR_ID = "vendor_id"; String BODY = "body"; } /** Fully-qualified field names. */ private interface Qualified { String SESSIONS_SEARCH_SESSION_ID = Tables.SESSIONS_SEARCH + "." + SessionsSearchColumns.SESSION_ID; String VENDORS_SEARCH_VENDOR_ID = Tables.VENDORS_SEARCH + "." + VendorsSearchColumns.VENDOR_ID; String SESSIONS_SEARCH = Tables.SESSIONS_SEARCH + "(" + SessionsSearchColumns.SESSION_ID + "," + SessionsSearchColumns.BODY + ")"; String VENDORS_SEARCH = Tables.VENDORS_SEARCH + "(" + VendorsSearchColumns.VENDOR_ID + "," + VendorsSearchColumns.BODY + ")"; } /** {@code REFERENCES} clauses. */ private interface References { String BLOCK_ID = "REFERENCES " + Tables.BLOCKS + "(" + Blocks.BLOCK_ID + ")"; String TRACK_ID = "REFERENCES " + Tables.TRACKS + "(" + Tracks.TRACK_ID + ")"; String ROOM_ID = "REFERENCES " + Tables.ROOMS + "(" + Rooms.ROOM_ID + ")"; String SESSION_ID = "REFERENCES " + Tables.SESSIONS + "(" + Sessions.SESSION_ID + ")"; String SPEAKER_ID = "REFERENCES " + Tables.SPEAKERS + "(" + Speakers.SPEAKER_ID + ")"; String VENDOR_ID = "REFERENCES " + Tables.VENDORS + "(" + Vendors.VENDOR_ID + ")"; } private interface Subquery { /** * Subquery used to build the {@link SessionsSearchColumns#BODY} string * used for indexing {@link Sessions} content. */ String SESSIONS_BODY = "(new." + Sessions.SESSION_TITLE + "||'; '||new." + Sessions.SESSION_ABSTRACT + "||'; '||" + "coalesce(new." + Sessions.SESSION_KEYWORDS + ", '')" + ")"; /** * Subquery used to build the {@link VendorsSearchColumns#BODY} string * used for indexing {@link Vendors} content. */ String VENDORS_BODY = "(new." + Vendors.VENDOR_NAME + "||'; '||new." + Vendors.VENDOR_DESC + "||'; '||new." + Vendors.VENDOR_PRODUCT_DESC + ")"; } public ScheduleDatabase(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + Tables.BLOCKS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + BlocksColumns.BLOCK_ID + " TEXT NOT NULL," + BlocksColumns.BLOCK_TITLE + " TEXT NOT NULL," + BlocksColumns.BLOCK_START + " INTEGER NOT NULL," + BlocksColumns.BLOCK_END + " INTEGER NOT NULL," + BlocksColumns.BLOCK_TYPE + " TEXT," + "UNIQUE (" + BlocksColumns.BLOCK_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.TRACKS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + TracksColumns.TRACK_ID + " TEXT NOT NULL," + TracksColumns.TRACK_NAME + " TEXT," + TracksColumns.TRACK_COLOR + " INTEGER," + TracksColumns.TRACK_ABSTRACT + " TEXT," + "UNIQUE (" + TracksColumns.TRACK_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.ROOMS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + RoomsColumns.ROOM_ID + " TEXT NOT NULL," + RoomsColumns.ROOM_NAME + " TEXT," + RoomsColumns.ROOM_FLOOR + " TEXT," + "UNIQUE (" + RoomsColumns.ROOM_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.SESSIONS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SyncColumns.UPDATED + " INTEGER NOT NULL," + SessionsColumns.SESSION_ID + " TEXT NOT NULL," + Sessions.BLOCK_ID + " TEXT " + References.BLOCK_ID + "," + Sessions.ROOM_ID + " TEXT " + References.ROOM_ID + "," + SessionsColumns.SESSION_LEVEL + " TEXT," + SessionsColumns.SESSION_TITLE + " TEXT," + SessionsColumns.SESSION_ABSTRACT + " TEXT," + SessionsColumns.SESSION_REQUIREMENTS + " TEXT," + SessionsColumns.SESSION_KEYWORDS + " TEXT," + SessionsColumns.SESSION_HASHTAG + " TEXT," + SessionsColumns.SESSION_SLUG + " TEXT," + SessionsColumns.SESSION_URL + " TEXT," + SessionsColumns.SESSION_MODERATOR_URL + " TEXT," + SessionsColumns.SESSION_YOUTUBE_URL + " TEXT," + SessionsColumns.SESSION_PDF_URL + " TEXT," + SessionsColumns.SESSION_FEEDBACK_URL + " TEXT," + SessionsColumns.SESSION_NOTES_URL + " TEXT," + SessionsColumns.SESSION_STARRED + " INTEGER NOT NULL DEFAULT 0," + "UNIQUE (" + SessionsColumns.SESSION_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.SPEAKERS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SyncColumns.UPDATED + " INTEGER NOT NULL," + SpeakersColumns.SPEAKER_ID + " TEXT NOT NULL," + SpeakersColumns.SPEAKER_NAME + " TEXT," + SpeakersColumns.SPEAKER_IMAGE_URL + " TEXT," + SpeakersColumns.SPEAKER_COMPANY + " TEXT," + SpeakersColumns.SPEAKER_ABSTRACT + " TEXT," + SpeakersColumns.SPEAKER_URL+ " TEXT," + "UNIQUE (" + SpeakersColumns.SPEAKER_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.SESSIONS_SPEAKERS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SessionsSpeakers.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + "," + SessionsSpeakers.SPEAKER_ID + " TEXT NOT NULL " + References.SPEAKER_ID + "," + "UNIQUE (" + SessionsSpeakers.SESSION_ID + "," + SessionsSpeakers.SPEAKER_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.SESSIONS_TRACKS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SessionsTracks.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + "," + SessionsTracks.TRACK_ID + " TEXT NOT NULL " + References.TRACK_ID + "," + "UNIQUE (" + SessionsTracks.SESSION_ID + "," + SessionsTracks.TRACK_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.VENDORS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SyncColumns.UPDATED + " INTEGER NOT NULL," + VendorsColumns.VENDOR_ID + " TEXT NOT NULL," + Vendors.TRACK_ID + " TEXT " + References.TRACK_ID + "," + VendorsColumns.VENDOR_NAME + " TEXT," + VendorsColumns.VENDOR_LOCATION + " TEXT," + VendorsColumns.VENDOR_DESC + " TEXT," + VendorsColumns.VENDOR_URL + " TEXT," + VendorsColumns.VENDOR_PRODUCT_DESC + " TEXT," + VendorsColumns.VENDOR_LOGO_URL + " TEXT," + VendorsColumns.VENDOR_STARRED + " INTEGER," + "UNIQUE (" + VendorsColumns.VENDOR_ID + ") ON CONFLICT REPLACE)"); createSessionsSearch(db); createVendorsSearch(db); db.execSQL("CREATE TABLE " + Tables.SEARCH_SUGGEST + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SearchManager.SUGGEST_COLUMN_TEXT_1 + " TEXT NOT NULL)"); } /** * Create triggers that automatically build {@link Tables#SESSIONS_SEARCH} * as values are changed in {@link Tables#SESSIONS}. */ private static void createSessionsSearch(SQLiteDatabase db) { // Using the "porter" tokenizer for simple stemming, so that // "frustration" matches "frustrated." db.execSQL("CREATE VIRTUAL TABLE " + Tables.SESSIONS_SEARCH + " USING fts3(" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SessionsSearchColumns.BODY + " TEXT NOT NULL," + SessionsSearchColumns.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + "," + "UNIQUE (" + SessionsSearchColumns.SESSION_ID + ") ON CONFLICT REPLACE," + "tokenize=porter)"); // TODO: handle null fields in body, which cause trigger to fail // TODO: implement update trigger, not currently exercised db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_SEARCH_INSERT + " AFTER INSERT ON " + Tables.SESSIONS + " BEGIN INSERT INTO " + Qualified.SESSIONS_SEARCH + " " + " VALUES(new." + Sessions.SESSION_ID + ", " + Subquery.SESSIONS_BODY + ");" + " END;"); db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_SEARCH_DELETE + " AFTER DELETE ON " + Tables.SESSIONS + " BEGIN DELETE FROM " + Tables.SESSIONS_SEARCH + " " + " WHERE " + Qualified.SESSIONS_SEARCH_SESSION_ID + "=old." + Sessions.SESSION_ID + ";" + " END;"); db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_SEARCH_UPDATE + " AFTER UPDATE ON " + Tables.SESSIONS + " BEGIN UPDATE sessions_search SET " + SessionsSearchColumns.BODY + " = " + Subquery.SESSIONS_BODY + " WHERE session_id = old.session_id" + "; END;"); } /** * Create triggers that automatically build {@link Tables#VENDORS_SEARCH} as * values are changed in {@link Tables#VENDORS}. */ private static void createVendorsSearch(SQLiteDatabase db) { // Using the "porter" tokenizer for simple stemming, so that // "frustration" matches "frustrated." db.execSQL("CREATE VIRTUAL TABLE " + Tables.VENDORS_SEARCH + " USING fts3(" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + VendorsSearchColumns.BODY + " TEXT NOT NULL," + VendorsSearchColumns.VENDOR_ID + " TEXT NOT NULL " + References.VENDOR_ID + "," + "UNIQUE (" + VendorsSearchColumns.VENDOR_ID + ") ON CONFLICT REPLACE," + "tokenize=porter)"); // TODO: handle null fields in body, which cause trigger to fail // TODO: implement update trigger, not currently exercised db.execSQL("CREATE TRIGGER " + Triggers.VENDORS_SEARCH_INSERT + " AFTER INSERT ON " + Tables.VENDORS + " BEGIN INSERT INTO " + Qualified.VENDORS_SEARCH + " " + " VALUES(new." + Vendors.VENDOR_ID + ", " + Subquery.VENDORS_BODY + ");" + " END;"); db.execSQL("CREATE TRIGGER " + Triggers.VENDORS_SEARCH_DELETE + " AFTER DELETE ON " + Tables.VENDORS + " BEGIN DELETE FROM " + Tables.VENDORS_SEARCH + " " + " WHERE " + Qualified.VENDORS_SEARCH_VENDOR_ID + "=old." + Vendors.VENDOR_ID + ";" + " END;"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.d(TAG, "onUpgrade() from " + oldVersion + " to " + newVersion); // NOTE: This switch statement is designed to handle cascading database // updates, starting at the current version and falling through to all // future upgrade cases. Only use "break;" when you want to drop and // recreate the entire database. int version = oldVersion; switch (version) { case VER_LAUNCH: // Version 22 added column for session feedback URL. db.execSQL("ALTER TABLE " + Tables.SESSIONS + " ADD COLUMN " + SessionsColumns.SESSION_FEEDBACK_URL + " TEXT"); version = VER_SESSION_FEEDBACK_URL; case VER_SESSION_FEEDBACK_URL: // Version 23 added columns for session official notes URL and slug. db.execSQL("ALTER TABLE " + Tables.SESSIONS + " ADD COLUMN " + SessionsColumns.SESSION_NOTES_URL + " TEXT"); db.execSQL("ALTER TABLE " + Tables.SESSIONS + " ADD COLUMN " + SessionsColumns.SESSION_SLUG + " TEXT"); version = VER_SESSION_NOTES_URL_SLUG; } Log.d(TAG, "after upgrade logic, at version " + version); if (version != DATABASE_VERSION) { Log.w(TAG, "Destroying old data during upgrade"); db.execSQL("DROP TABLE IF EXISTS " + Tables.BLOCKS); db.execSQL("DROP TABLE IF EXISTS " + Tables.TRACKS); db.execSQL("DROP TABLE IF EXISTS " + Tables.ROOMS); db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS); db.execSQL("DROP TABLE IF EXISTS " + Tables.SPEAKERS); db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_SPEAKERS); db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_TRACKS); db.execSQL("DROP TABLE IF EXISTS " + Tables.VENDORS); db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_SEARCH_INSERT); db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_SEARCH_DELETE); db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_SEARCH); db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.VENDORS_SEARCH_INSERT); db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.VENDORS_SEARCH_DELETE); db.execSQL("DROP TABLE IF EXISTS " + Tables.VENDORS_SEARCH); db.execSQL("DROP TABLE IF EXISTS " + Tables.SEARCH_SUGGEST); onCreate(db); } } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import java.util.ArrayList; /** * A <em>really</em> dumb implementation of the {@link Menu} interface, that's only useful for our * old-actionbar purposes. See <code>com.android.internal.view.menu.MenuBuilder</code> in AOSP for * a more complete implementation. */ public class SimpleMenu implements Menu { private Context mContext; private Resources mResources; private ArrayList<SimpleMenuItem> mItems; public SimpleMenu(Context context) { mContext = context; mResources = context.getResources(); mItems = new ArrayList<SimpleMenuItem>(); } public Context getContext() { return mContext; } public Resources getResources() { return mResources; } public MenuItem add(CharSequence title) { return addInternal(0, 0, title); } public MenuItem add(int titleRes) { return addInternal(0, 0, mResources.getString(titleRes)); } public MenuItem add(int groupId, int itemId, int order, CharSequence title) { return addInternal(itemId, order, title); } public MenuItem add(int groupId, int itemId, int order, int titleRes) { return addInternal(itemId, order, mResources.getString(titleRes)); } /** * Adds an item to the menu. The other add methods funnel to this. */ private MenuItem addInternal(int itemId, int order, CharSequence title) { final SimpleMenuItem item = new SimpleMenuItem(this, itemId, order, title); mItems.add(findInsertIndex(mItems, order), item); return item; } private static int findInsertIndex(ArrayList<? extends MenuItem> items, int order) { for (int i = items.size() - 1; i >= 0; i--) { MenuItem item = items.get(i); if (item.getOrder() <= order) { return i + 1; } } return 0; } public int findItemIndex(int id) { final int size = size(); for (int i = 0; i < size; i++) { SimpleMenuItem item = mItems.get(i); if (item.getItemId() == id) { return i; } } return -1; } public void removeItem(int itemId) { removeItemAtInt(findItemIndex(itemId)); } private void removeItemAtInt(int index) { if ((index < 0) || (index >= mItems.size())) { return; } mItems.remove(index); } public void clear() { mItems.clear(); } public MenuItem findItem(int id) { final int size = size(); for (int i = 0; i < size; i++) { SimpleMenuItem item = mItems.get(i); if (item.getItemId() == id) { return item; } } return null; } public int size() { return mItems.size(); } public MenuItem getItem(int index) { return mItems.get(index); } // Unsupported operations. public SubMenu addSubMenu(CharSequence charSequence) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public SubMenu addSubMenu(int titleRes) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public int addIntentOptions(int i, int i1, int i2, ComponentName componentName, Intent[] intents, Intent intent, int i3, MenuItem[] menuItems) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void removeGroup(int i) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void setGroupCheckable(int i, boolean b, boolean b1) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void setGroupVisible(int i, boolean b) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void setGroupEnabled(int i, boolean b) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public boolean hasVisibleItems() { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void close() { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public boolean performShortcut(int i, KeyEvent keyEvent, int i1) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public boolean isShortcutKey(int i, KeyEvent keyEvent) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public boolean performIdentifierAction(int i, int i1) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void setQwertyMode(boolean b) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } }
Java
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import java.util.ArrayList; import java.util.Collections; /** * Provides static methods for creating {@code List} instances easily, and other * utility methods for working with lists. */ public class Lists { /** * Creates an empty {@code ArrayList} instance. * * <p><b>Note:</b> if you only need an <i>immutable</i> empty List, use * {@link Collections#emptyList} instead. * * @return a newly-created, initially-empty {@code ArrayList} */ public static <E> ArrayList<E> newArrayList() { return new ArrayList<E>(); } /** * Creates a resizable {@code ArrayList} instance containing the given * elements. * * <p><b>Note:</b> due to a bug in javac 1.5.0_06, we cannot support the * following: * * <p>{@code List<Base> list = Lists.newArrayList(sub1, sub2);} * * <p>where {@code sub1} and {@code sub2} are references to subtypes of * {@code Base}, not of {@code Base} itself. To get around this, you must * use: * * <p>{@code List<Base> list = Lists.<Base>newArrayList(sub1, sub2);} * * @param elements the elements that the list should contain, in order * @return a newly-created {@code ArrayList} containing those elements */ public static <E> ArrayList<E> newArrayList(E... elements) { int capacity = (elements.length * 110) / 100 + 5; ArrayList<E> list = new ArrayList<E>(capacity); Collections.addAll(list, elements); return list; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import com.google.android.apps.iosched.service.SyncService; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.util.EntityUtils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Environment; import android.text.TextUtils; import android.util.Log; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * Helper class for fetching and disk-caching images from the web. */ public class BitmapUtils { private static final String TAG = "BitmapUtils"; // TODO: for concurrent connections, DefaultHttpClient isn't great, consider other options // that still allow for sharing resources across bitmap fetches. public static interface OnFetchCompleteListener { public void onFetchComplete(Object cookie, Bitmap result); } /** * Only call this method from the main (UI) thread. The {@link OnFetchCompleteListener} callback * be invoked on the UI thread, but image fetching will be done in an {@link AsyncTask}. */ public static void fetchImage(final Context context, final String url, final OnFetchCompleteListener callback) { fetchImage(context, url, null, null, callback); } /** * Only call this method from the main (UI) thread. The {@link OnFetchCompleteListener} callback * be invoked on the UI thread, but image fetching will be done in an {@link AsyncTask}. * * @param cookie An arbitrary object that will be passed to the callback. */ public static void fetchImage(final Context context, final String url, final BitmapFactory.Options decodeOptions, final Object cookie, final OnFetchCompleteListener callback) { new AsyncTask<String, Void, Bitmap>() { @Override protected Bitmap doInBackground(String... params) { final String url = params[0]; if (TextUtils.isEmpty(url)) { return null; } // First compute the cache key and cache file path for this URL File cacheFile = null; try { MessageDigest mDigest = MessageDigest.getInstance("SHA-1"); mDigest.update(url.getBytes()); final String cacheKey = bytesToHexString(mDigest.digest()); if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { cacheFile = new File( Environment.getExternalStorageDirectory() + File.separator + "Android" + File.separator + "data" + File.separator + context.getPackageName() + File.separator + "cache" + File.separator + "bitmap_" + cacheKey + ".tmp"); } } catch (NoSuchAlgorithmException e) { // Oh well, SHA-1 not available (weird), don't cache bitmaps. } if (cacheFile != null && cacheFile.exists()) { Bitmap cachedBitmap = BitmapFactory.decodeFile( cacheFile.toString(), decodeOptions); if (cachedBitmap != null) { return cachedBitmap; } } try { // TODO: check for HTTP caching headers final HttpClient httpClient = SyncService.getHttpClient( context.getApplicationContext()); final HttpResponse resp = httpClient.execute(new HttpGet(url)); final HttpEntity entity = resp.getEntity(); final int statusCode = resp.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK || entity == null) { return null; } final byte[] respBytes = EntityUtils.toByteArray(entity); // Write response bytes to cache. if (cacheFile != null) { try { cacheFile.getParentFile().mkdirs(); cacheFile.createNewFile(); FileOutputStream fos = new FileOutputStream(cacheFile); fos.write(respBytes); fos.close(); } catch (FileNotFoundException e) { Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e); } catch (IOException e) { Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e); } } // Decode the bytes and return the bitmap. return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length, decodeOptions); } catch (Exception e) { Log.w(TAG, "Problem while loading image: " + e.toString(), e); } return null; } @Override protected void onPostExecute(Bitmap result) { callback.onFetchComplete(cookie, result); } }.execute(url); } private static String bytesToHexString(byte[] bytes) { // http://stackoverflow.com/questions/332079 StringBuffer sb = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(0xFF & bytes[i]); if (hex.length() == 1) { sb.append('0'); } sb.append(hex); } return sb.toString(); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import com.google.android.apps.analytics.GoogleAnalyticsTracker; import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Build; import android.preference.PreferenceManager; import android.util.Log; /** * Helper singleton class for the Google Analytics tracking library. */ public class AnalyticsUtils { private static final String TAG = "AnalyticsUtils"; GoogleAnalyticsTracker mTracker; private Context mApplicationContext; /** * The analytics tracking code for the app. */ // TODO: insert your Analytics UA code here. private static final String UACODE = "INSERT_YOUR_ANALYTICS_UA_CODE_HERE"; private static final int VISITOR_SCOPE = 1; private static final String FIRST_RUN_KEY = "firstRun"; private static final boolean ANALYTICS_ENABLED = true; private static AnalyticsUtils sInstance; /** * Returns the global {@link AnalyticsUtils} singleton object, creating one if necessary. */ public static AnalyticsUtils getInstance(Context context) { if (!ANALYTICS_ENABLED) { return sEmptyAnalyticsUtils; } if (sInstance == null) { if (context == null) { return sEmptyAnalyticsUtils; } sInstance = new AnalyticsUtils(context); } return sInstance; } private AnalyticsUtils(Context context) { if (context == null) { // This should only occur for the empty Analytics utils object. return; } mApplicationContext = context.getApplicationContext(); mTracker = GoogleAnalyticsTracker.getInstance(); // Unfortunately this needs to be synchronous. mTracker.start(UACODE, 300, mApplicationContext); Log.d(TAG, "Initializing Analytics"); // Since visitor CV's should only be declared the first time an app runs, check if // it's run before. Add as necessary. SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( mApplicationContext); final boolean firstRun = prefs.getBoolean(FIRST_RUN_KEY, true); if (firstRun) { Log.d(TAG, "Analytics firstRun"); String apiLevel = Integer.toString(Build.VERSION.SDK_INT); String model = Build.MODEL; mTracker.setCustomVar(1, "apiLevel", apiLevel, VISITOR_SCOPE); mTracker.setCustomVar(2, "model", model, VISITOR_SCOPE); // Close out so we never run this block again, unless app is removed & = // reinstalled. prefs.edit().putBoolean(FIRST_RUN_KEY, false).commit(); } } public void trackEvent(final String category, final String action, final String label, final int value) { // We wrap the call in an AsyncTask since the Google Analytics library writes to disk // on its calling thread. new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { try { mTracker.trackEvent(category, action, label, value); Log.d(TAG, "iosched Analytics trackEvent: " + category + " / " + action + " / " + label + " / " + value); } catch (Exception e) { // We don't want to crash if there's an Analytics library exception. Log.w(TAG, "iosched Analytics trackEvent error: " + category + " / " + action + " / " + label + " / " + value, e); } return null; } }.execute(); } public void trackPageView(final String path) { // We wrap the call in an AsyncTask since the Google Analytics library writes to disk // on its calling thread. new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { try { mTracker.trackPageView(path); Log.d(TAG, "iosched Analytics trackPageView: " + path); } catch (Exception e) { // We don't want to crash if there's an Analytics library exception. Log.w(TAG, "iosched Analytics trackPageView error: " + path, e); } return null; } }.execute(); } /** * Empty instance for use when Analytics is disabled or there was no Context available. */ private static AnalyticsUtils sEmptyAnalyticsUtils = new AnalyticsUtils(null) { @Override public void trackEvent(String category, String action, String label, int value) {} @Override public void trackPageView(String path) {} }; }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.text.format.DateUtils; import java.io.IOException; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.HREF; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.LINK; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.REL; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.TITLE; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.UPDATED; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.END_TAG; import static org.xmlpull.v1.XmlPullParser.START_TAG; import static org.xmlpull.v1.XmlPullParser.TEXT; public class WorksheetEntry { private static final String REL_LISTFEED = "http://schemas.google.com/spreadsheets/2006#listfeed"; private long mUpdated; private String mTitle; private String mListFeed; public long getUpdated() { return mUpdated; } public String getTitle() { return mTitle; } public String getListFeed() { return mListFeed; } @Override public String toString() { return "title=" + mTitle + ", updated=" + mUpdated + " (" + DateUtils.getRelativeTimeSpanString(mUpdated) + ")"; } public static WorksheetEntry fromParser(XmlPullParser parser) throws XmlPullParserException, IOException { final int depth = parser.getDepth(); final WorksheetEntry entry = new WorksheetEntry(); String tag = null; int type; while (((type = parser.next()) != END_TAG || parser.getDepth() > depth) && type != END_DOCUMENT) { if (type == START_TAG) { tag = parser.getName(); if (LINK.equals(tag)) { final String rel = parser.getAttributeValue(null, REL); final String href = parser.getAttributeValue(null, HREF); if (REL_LISTFEED.equals(rel)) { entry.mListFeed = href; } } } else if (type == END_TAG) { tag = null; } else if (type == TEXT) { final String text = parser.getText(); if (TITLE.equals(tag)) { entry.mTitle = text; } else if (UPDATED.equals(tag)) { entry.mUpdated = ParserUtils.parseTime(text); } } } return entry; } }
Java
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Modifications: * -Imported from AOSP frameworks/base/core/java/com/android/internal/content * -Changed package name */ package com.google.android.apps.iosched.util; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.text.TextUtils; import android.util.Log; import java.util.ArrayList; import java.util.Arrays; import java.util.Map; /** * Helper for building selection clauses for {@link SQLiteDatabase}. Each * appended clause is combined using {@code AND}. This class is <em>not</em> * thread safe. */ public class SelectionBuilder { private static final String TAG = "SelectionBuilder"; private static final boolean LOGV = false; private String mTable = null; private Map<String, String> mProjectionMap = Maps.newHashMap(); private StringBuilder mSelection = new StringBuilder(); private ArrayList<String> mSelectionArgs = Lists.newArrayList(); /** * Reset any internal state, allowing this builder to be recycled. */ public SelectionBuilder reset() { mTable = null; mSelection.setLength(0); mSelectionArgs.clear(); return this; } /** * Append the given selection clause to the internal state. Each clause is * surrounded with parenthesis and combined using {@code AND}. */ public SelectionBuilder where(String selection, String... selectionArgs) { if (TextUtils.isEmpty(selection)) { if (selectionArgs != null && selectionArgs.length > 0) { throw new IllegalArgumentException( "Valid selection required when including arguments="); } // Shortcut when clause is empty return this; } if (mSelection.length() > 0) { mSelection.append(" AND "); } mSelection.append("(").append(selection).append(")"); if (selectionArgs != null) { for (String arg : selectionArgs) { mSelectionArgs.add(arg); } } return this; } public SelectionBuilder table(String table) { mTable = table; return this; } private void assertTable() { if (mTable == null) { throw new IllegalStateException("Table not specified"); } } public SelectionBuilder mapToTable(String column, String table) { mProjectionMap.put(column, table + "." + column); return this; } public SelectionBuilder map(String fromColumn, String toClause) { mProjectionMap.put(fromColumn, toClause + " AS " + fromColumn); return this; } /** * Return selection string for current internal state. * * @see #getSelectionArgs() */ public String getSelection() { return mSelection.toString(); } /** * Return selection arguments for current internal state. * * @see #getSelection() */ public String[] getSelectionArgs() { return mSelectionArgs.toArray(new String[mSelectionArgs.size()]); } private void mapColumns(String[] columns) { for (int i = 0; i < columns.length; i++) { final String target = mProjectionMap.get(columns[i]); if (target != null) { columns[i] = target; } } } @Override public String toString() { return "SelectionBuilder[table=" + mTable + ", selection=" + getSelection() + ", selectionArgs=" + Arrays.toString(getSelectionArgs()) + "]"; } /** * Execute query using the current internal state as {@code WHERE} clause. */ public Cursor query(SQLiteDatabase db, String[] columns, String orderBy) { return query(db, columns, null, null, orderBy, null); } /** * Execute query using the current internal state as {@code WHERE} clause. */ public Cursor query(SQLiteDatabase db, String[] columns, String groupBy, String having, String orderBy, String limit) { assertTable(); if (columns != null) mapColumns(columns); if (LOGV) Log.v(TAG, "query(columns=" + Arrays.toString(columns) + ") " + this); return db.query(mTable, columns, getSelection(), getSelectionArgs(), groupBy, having, orderBy, limit); } /** * Execute update using the current internal state as {@code WHERE} clause. */ public int update(SQLiteDatabase db, ContentValues values) { assertTable(); if (LOGV) Log.v(TAG, "update() " + this); return db.update(mTable, values, getSelection(), getSelectionArgs()); } /** * Execute delete using the current internal state as {@code WHERE} clause. */ public int delete(SQLiteDatabase db) { assertTable(); if (LOGV) Log.v(TAG, "delete() " + this); return db.delete(mTable, getSelection(), getSelectionArgs()); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import android.view.MotionEvent; /** * A utility class that emulates multitouch APIs available in Android 2.0+. */ public class MotionEventUtils { public static final int ACTION_MASK = 0xff; public static final int ACTION_POINTER_UP = 0x6; public static final int ACTION_POINTER_INDEX_MASK = 0x0000ff00; public static final int ACTION_POINTER_INDEX_SHIFT = 8; public static boolean sMultiTouchApiAvailable; static { try { MotionEvent.class.getMethod("getPointerId", new Class[]{int.class}); sMultiTouchApiAvailable = true; } catch (NoSuchMethodException nsme) { sMultiTouchApiAvailable = false; } } public static float getX(MotionEvent ev, int pointerIndex) { if (sMultiTouchApiAvailable) { return WrappedStaticMotionEvent.getX(ev, pointerIndex); } else { return ev.getX(); } } public static float getY(MotionEvent ev, int pointerIndex) { if (sMultiTouchApiAvailable) { return WrappedStaticMotionEvent.getY(ev, pointerIndex); } else { return ev.getY(); } } public static int getPointerId(MotionEvent ev, int pointerIndex) { if (sMultiTouchApiAvailable) { return WrappedStaticMotionEvent.getPointerId(ev, pointerIndex); } else { return 0; } } public static int findPointerIndex(MotionEvent ev, int pointerId) { if (sMultiTouchApiAvailable) { return WrappedStaticMotionEvent.findPointerIndex(ev, pointerId); } else { return (pointerId == 0) ? 0 : -1; } } /** * A wrapper around newer (SDK level 5) MotionEvent APIs. This class only gets loaded * if it is determined that these new APIs exist on the device. */ private static class WrappedStaticMotionEvent { public static float getX(MotionEvent ev, int pointerIndex) { return ev.getX(pointerIndex); } public static float getY(MotionEvent ev, int pointerIndex) { return ev.getY(pointerIndex); } public static int getPointerId(MotionEvent ev, int pointerIndex) { return ev.getPointerId(pointerIndex); } public static int findPointerIndex(MotionEvent ev, int pointerId) { return ev.findPointerIndex(pointerId); } } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import android.content.Intent; import android.graphics.drawable.Drawable; import android.view.ContextMenu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; /** * A <em>really</em> dumb implementation of the {@link MenuItem} interface, that's only useful for * our old-actionbar purposes. See <code>com.android.internal.view.menu.MenuItemImpl</code> in * AOSP for a more complete implementation. */ public class SimpleMenuItem implements MenuItem { private SimpleMenu mMenu; private final int mId; private final int mOrder; private CharSequence mTitle; private CharSequence mTitleCondensed; private Drawable mIconDrawable; private int mIconResId = 0; private boolean mEnabled = true; public SimpleMenuItem(SimpleMenu menu, int id, int order, CharSequence title) { mMenu = menu; mId = id; mOrder = order; mTitle = title; } public int getItemId() { return mId; } public int getOrder() { return mOrder; } public MenuItem setTitle(CharSequence title) { mTitle = title; return this; } public MenuItem setTitle(int titleRes) { return setTitle(mMenu.getContext().getString(titleRes)); } public CharSequence getTitle() { return mTitle; } public MenuItem setTitleCondensed(CharSequence title) { mTitleCondensed = title; return this; } public CharSequence getTitleCondensed() { return mTitleCondensed != null ? mTitleCondensed : mTitle; } public MenuItem setIcon(Drawable icon) { mIconResId = 0; mIconDrawable = icon; return this; } public MenuItem setIcon(int iconResId) { mIconDrawable = null; mIconResId = iconResId; return this; } public Drawable getIcon() { if (mIconDrawable != null) { return mIconDrawable; } if (mIconResId != 0) { return mMenu.getResources().getDrawable(mIconResId); } return null; } public MenuItem setEnabled(boolean enabled) { mEnabled = enabled; return this; } public boolean isEnabled() { return mEnabled; } // No-op operations. We use no-ops to allow inflation from menu XML. public int getGroupId() { return 0; } public View getActionView() { return null; } public MenuItem setIntent(Intent intent) { // Noop return this; } public Intent getIntent() { return null; } public MenuItem setShortcut(char c, char c1) { // Noop return this; } public MenuItem setNumericShortcut(char c) { // Noop return this; } public char getNumericShortcut() { return 0; } public MenuItem setAlphabeticShortcut(char c) { // Noop return this; } public char getAlphabeticShortcut() { return 0; } public MenuItem setCheckable(boolean b) { // Noop return this; } public boolean isCheckable() { return false; } public MenuItem setChecked(boolean b) { // Noop return this; } public boolean isChecked() { return false; } public MenuItem setVisible(boolean b) { // Noop return this; } public boolean isVisible() { return true; } public boolean hasSubMenu() { return false; } public SubMenu getSubMenu() { return null; } public MenuItem setOnMenuItemClickListener( OnMenuItemClickListener onMenuItemClickListener) { // Noop return this; } public ContextMenu.ContextMenuInfo getMenuInfo() { return null; } public void setShowAsAction(int i) { // Noop } public MenuItem setActionView(View view) { // Noop return this; } public MenuItem setActionView(int i) { // Noop return this; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.ui.HomeActivity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; /** * A class that handles some common activity-related functionality in the app, such as setting up * the action bar. This class provides functionality useful for both phones and tablets, and does * not require any Android 3.0-specific features. */ public class ActivityHelper { protected Activity mActivity; /** * Factory method for creating {@link ActivityHelper} objects for a given activity. Depending * on which device the app is running, either a basic helper or Honeycomb-specific helper will * be returned. */ public static ActivityHelper createInstance(Activity activity) { return UIUtils.isHoneycomb() ? new ActivityHelperHoneycomb(activity) : new ActivityHelper(activity); } protected ActivityHelper(Activity activity) { mActivity = activity; } public void onPostCreate(Bundle savedInstanceState) { // Create the action bar SimpleMenu menu = new SimpleMenu(mActivity); mActivity.onCreatePanelMenu(Window.FEATURE_OPTIONS_PANEL, menu); // TODO: call onPreparePanelMenu here as well for (int i = 0; i < menu.size(); i++) { MenuItem item = menu.getItem(i); addActionButtonCompatFromMenuItem(item); } } public boolean onCreateOptionsMenu(Menu menu) { mActivity.getMenuInflater().inflate(R.menu.default_menu_items, menu); return false; } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_search: goSearch(); return true; } return false; } public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU) { return true; } return false; } public boolean onKeyLongPress(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { goHome(); return true; } return false; } /** * Method, to be called in <code>onPostCreate</code>, that sets up this activity as the * home activity for the app. */ public void setupHomeActivity() { } /** * Method, to be called in <code>onPostCreate</code>, that sets up this activity as a * sub-activity in the app. */ public void setupSubActivity() { } /** * Invoke "home" action, returning to {@link com.google.android.apps.iosched.ui.HomeActivity}. */ public void goHome() { if (mActivity instanceof HomeActivity) { return; } final Intent intent = new Intent(mActivity, HomeActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); mActivity.startActivity(intent); if (!UIUtils.isHoneycomb()) { mActivity.overridePendingTransition(R.anim.home_enter, R.anim.home_exit); } } /** * Invoke "search" action, triggering a default search. */ public void goSearch() { mActivity.startSearch(null, false, Bundle.EMPTY, false); } /** * Sets up the action bar with the given title and accent color. If title is null, then * the app logo will be shown instead of a title. Otherwise, a home button and title are * visible. If color is null, then the default colorstrip is visible. */ public void setupActionBar(CharSequence title, int color) { final ViewGroup actionBarCompat = getActionBarCompat(); if (actionBarCompat == null) { return; } LinearLayout.LayoutParams springLayoutParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.FILL_PARENT); springLayoutParams.weight = 1; View.OnClickListener homeClickListener = new View.OnClickListener() { public void onClick(View view) { goHome(); } }; if (title != null) { // Add Home button addActionButtonCompat(R.drawable.ic_title_home, R.string.description_home, homeClickListener, true); // Add title text TextView titleText = new TextView(mActivity, null, R.attr.actionbarCompatTextStyle); titleText.setLayoutParams(springLayoutParams); titleText.setText(title); actionBarCompat.addView(titleText); } else { // Add logo ImageButton logo = new ImageButton(mActivity, null, R.attr.actionbarCompatLogoStyle); logo.setOnClickListener(homeClickListener); actionBarCompat.addView(logo); // Add spring (dummy view to align future children to the right) View spring = new View(mActivity); spring.setLayoutParams(springLayoutParams); actionBarCompat.addView(spring); } setActionBarColor(color); } /** * Sets the action bar color to the given color. */ public void setActionBarColor(int color) { if (color == 0) { return; } final View colorstrip = mActivity.findViewById(R.id.colorstrip); if (colorstrip == null) { return; } colorstrip.setBackgroundColor(color); } /** * Sets the action bar title to the given string. */ public void setActionBarTitle(CharSequence title) { ViewGroup actionBar = getActionBarCompat(); if (actionBar == null) { return; } TextView titleText = (TextView) actionBar.findViewById(R.id.actionbar_compat_text); if (titleText != null) { titleText.setText(title); } } /** * Returns the {@link ViewGroup} for the action bar on phones (compatibility action bar). * Can return null, and will return null on Honeycomb. */ public ViewGroup getActionBarCompat() { return (ViewGroup) mActivity.findViewById(R.id.actionbar_compat); } /** * Adds an action bar button to the compatibility action bar (on phones). */ private View addActionButtonCompat(int iconResId, int textResId, View.OnClickListener clickListener, boolean separatorAfter) { final ViewGroup actionBar = getActionBarCompat(); if (actionBar == null) { return null; } // Create the separator ImageView separator = new ImageView(mActivity, null, R.attr.actionbarCompatSeparatorStyle); separator.setLayoutParams( new ViewGroup.LayoutParams(2, ViewGroup.LayoutParams.FILL_PARENT)); // Create the button ImageButton actionButton = new ImageButton(mActivity, null, R.attr.actionbarCompatButtonStyle); actionButton.setLayoutParams(new ViewGroup.LayoutParams( (int) mActivity.getResources().getDimension(R.dimen.actionbar_compat_height), ViewGroup.LayoutParams.FILL_PARENT)); actionButton.setImageResource(iconResId); actionButton.setScaleType(ImageView.ScaleType.CENTER); actionButton.setContentDescription(mActivity.getResources().getString(textResId)); actionButton.setOnClickListener(clickListener); // Add separator and button to the action bar in the desired order if (!separatorAfter) { actionBar.addView(separator); } actionBar.addView(actionButton); if (separatorAfter) { actionBar.addView(separator); } return actionButton; } /** * Adds an action button to the compatibility action bar, using menu information from a * {@link MenuItem}. If the menu item ID is <code>menu_refresh</code>, the menu item's state * can be changed to show a loading spinner using * {@link ActivityHelper#setRefreshActionButtonCompatState(boolean)}. */ private View addActionButtonCompatFromMenuItem(final MenuItem item) { final ViewGroup actionBar = getActionBarCompat(); if (actionBar == null) { return null; } // Create the separator ImageView separator = new ImageView(mActivity, null, R.attr.actionbarCompatSeparatorStyle); separator.setLayoutParams( new ViewGroup.LayoutParams(2, ViewGroup.LayoutParams.FILL_PARENT)); // Create the button ImageButton actionButton = new ImageButton(mActivity, null, R.attr.actionbarCompatButtonStyle); actionButton.setId(item.getItemId()); actionButton.setLayoutParams(new ViewGroup.LayoutParams( (int) mActivity.getResources().getDimension(R.dimen.actionbar_compat_height), ViewGroup.LayoutParams.FILL_PARENT)); actionButton.setImageDrawable(item.getIcon()); actionButton.setScaleType(ImageView.ScaleType.CENTER); actionButton.setContentDescription(item.getTitle()); actionButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mActivity.onMenuItemSelected(Window.FEATURE_OPTIONS_PANEL, item); } }); actionBar.addView(separator); actionBar.addView(actionButton); if (item.getItemId() == R.id.menu_refresh) { // Refresh buttons should be stateful, and allow for indeterminate progress indicators, // so add those. int buttonWidth = mActivity.getResources() .getDimensionPixelSize(R.dimen.actionbar_compat_height); int buttonWidthDiv3 = buttonWidth / 3; ProgressBar indicator = new ProgressBar(mActivity, null, R.attr.actionbarCompatProgressIndicatorStyle); LinearLayout.LayoutParams indicatorLayoutParams = new LinearLayout.LayoutParams( buttonWidthDiv3, buttonWidthDiv3); indicatorLayoutParams.setMargins(buttonWidthDiv3, buttonWidthDiv3, buttonWidth - 2 * buttonWidthDiv3, 0); indicator.setLayoutParams(indicatorLayoutParams); indicator.setVisibility(View.GONE); indicator.setId(R.id.menu_refresh_progress); actionBar.addView(indicator); } return actionButton; } /** * Sets the indeterminate loading state of a refresh button added with * {@link ActivityHelper#addActionButtonCompatFromMenuItem(android.view.MenuItem)} * (where the item ID was menu_refresh). */ public void setRefreshActionButtonCompatState(boolean refreshing) { View refreshButton = mActivity.findViewById(R.id.menu_refresh); View refreshIndicator = mActivity.findViewById(R.id.menu_refresh_progress); if (refreshButton != null) { refreshButton.setVisibility(refreshing ? View.GONE : View.VISIBLE); } if (refreshIndicator != null) { refreshIndicator.setVisibility(refreshing ? View.VISIBLE : View.GONE); } } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import java.lang.reflect.InvocationTargetException; public class ReflectionUtils { public static Object tryInvoke(Object target, String methodName, Object... args) { Class<?>[] argTypes = new Class<?>[args.length]; for (int i = 0; i < args.length; i++) { argTypes[i] = args[i].getClass(); } return tryInvoke(target, methodName, argTypes, args); } public static Object tryInvoke(Object target, String methodName, Class<?>[] argTypes, Object... args) { try { return target.getClass().getMethod(methodName, argTypes).invoke(target, args); } catch (NoSuchMethodException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } return null; } public static <E> E callWithDefault(Object target, String methodName, E defaultValue) { try { return (E) target.getClass().getMethod(methodName, (Class[]) null).invoke(target); } catch (NoSuchMethodException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } return defaultValue; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.provider.ScheduleContract.Rooms; import com.google.android.apps.iosched.ui.phone.MapActivity; import com.google.android.apps.iosched.ui.tablet.MapMultiPaneActivity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.preference.PreferenceManager; import android.text.Html; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.format.DateUtils; import android.text.method.LinkMovementMethod; import android.text.style.StyleSpan; import android.widget.TextView; import java.util.Formatter; import java.util.List; import java.util.Locale; import java.util.TimeZone; /** * An assortment of UI helpers. */ public class UIUtils { /** * Time zone to use when formatting all session times. To always use the * phone local time, use {@link TimeZone#getDefault()}. */ public static final TimeZone CONFERENCE_TIME_ZONE = TimeZone.getTimeZone("America/Los_Angeles"); public static final long CONFERENCE_START_MILLIS = ParserUtils.parseTime( "2011-05-10T09:00:00.000-07:00"); public static final long CONFERENCE_END_MILLIS = ParserUtils.parseTime( "2011-05-11T17:30:00.000-07:00"); public static final Uri CONFERENCE_URL = Uri.parse("http://www.google.com/events/io/2011/"); /** Flags used with {@link DateUtils#formatDateRange}. */ private static final int TIME_FLAGS = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_WEEKDAY; /** {@link StringBuilder} used for formatting time block. */ private static StringBuilder sBuilder = new StringBuilder(50); /** {@link Formatter} used for formatting time block. */ private static Formatter sFormatter = new Formatter(sBuilder, Locale.getDefault()); private static StyleSpan sBoldSpan = new StyleSpan(Typeface.BOLD); /** * Format and return the given {@link Blocks} and {@link Rooms} values using * {@link #CONFERENCE_TIME_ZONE}. */ public static String formatSessionSubtitle(long blockStart, long blockEnd, String roomName, Context context) { TimeZone.setDefault(CONFERENCE_TIME_ZONE); // NOTE: There is an efficient version of formatDateRange in Eclair and // beyond that allows you to recycle a StringBuilder. final CharSequence timeString = DateUtils.formatDateRange(context, blockStart, blockEnd, TIME_FLAGS); return context.getString(R.string.session_subtitle, timeString, roomName); } /** * Populate the given {@link TextView} with the requested text, formatting * through {@link Html#fromHtml(String)} when applicable. Also sets * {@link TextView#setMovementMethod} so inline links are handled. */ public static void setTextMaybeHtml(TextView view, String text) { if (TextUtils.isEmpty(text)) { view.setText(""); return; } if (text.contains("<") && text.contains(">")) { view.setText(Html.fromHtml(text)); view.setMovementMethod(LinkMovementMethod.getInstance()); } else { view.setText(text); } } public static void setSessionTitleColor(long blockStart, long blockEnd, TextView title, TextView subtitle) { long currentTimeMillis = System.currentTimeMillis(); int colorId = R.color.body_text_1; int subColorId = R.color.body_text_2; if (currentTimeMillis > blockEnd && currentTimeMillis < CONFERENCE_END_MILLIS) { colorId = subColorId = R.color.body_text_disabled; } final Resources res = title.getResources(); title.setTextColor(res.getColor(colorId)); subtitle.setTextColor(res.getColor(subColorId)); } /** * Given a snippet string with matching segments surrounded by curly * braces, turn those areas into bold spans, removing the curly braces. */ public static Spannable buildStyledSnippet(String snippet) { final SpannableStringBuilder builder = new SpannableStringBuilder(snippet); // Walk through string, inserting bold snippet spans int startIndex = -1, endIndex = -1, delta = 0; while ((startIndex = snippet.indexOf('{', endIndex)) != -1) { endIndex = snippet.indexOf('}', startIndex); // Remove braces from both sides builder.delete(startIndex - delta, startIndex - delta + 1); builder.delete(endIndex - delta - 1, endIndex - delta); // Insert bold style builder.setSpan(sBoldSpan, startIndex - delta, endIndex - delta - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); delta += 2; } return builder; } public static String getLastUsedTrackID(Context context) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); return sp.getString("last_track_id", null); } public static void setLastUsedTrackID(Context context, String trackID) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); sp.edit().putString("last_track_id", trackID).commit(); } private static final int BRIGHTNESS_THRESHOLD = 130; /** * Calculate whether a color is light or dark, based on a commonly known * brightness formula. * * @see {@literal http://en.wikipedia.org/wiki/HSV_color_space%23Lightness} */ public static boolean isColorDark(int color) { return ((30 * Color.red(color) + 59 * Color.green(color) + 11 * Color.blue(color)) / 100) <= BRIGHTNESS_THRESHOLD; } public static boolean isHoneycomb() { // Can use static final constants like HONEYCOMB, declared in later versions // of the OS since they are inlined at compile time. This is guaranteed behavior. return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; } public static boolean isTablet(Context context) { return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE; } public static boolean isHoneycombTablet(Context context) { return isHoneycomb() && isTablet(context); } public static long getCurrentTime(final Context context) { //SharedPreferences prefs = context.getSharedPreferences("mock_data", 0); //prefs.edit().commit(); //return prefs.getLong("mock_current_time", System.currentTimeMillis()); return System.currentTimeMillis(); } public static Drawable getIconForIntent(final Context context, Intent i) { PackageManager pm = context.getPackageManager(); List<ResolveInfo> infos = pm.queryIntentActivities(i, PackageManager.MATCH_DEFAULT_ONLY); if (infos.size() > 0) { return infos.get(0).loadIcon(pm); } return null; } public static Class getMapActivityClass(Context context) { if (UIUtils.isHoneycombTablet(context)) { return MapMultiPaneActivity.class; } return MapActivity.class; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import java.util.Collections; import java.util.EnumSet; import java.util.HashSet; import java.util.SortedSet; import java.util.TreeSet; /** * Provides static methods for creating mutable {@code Set} instances easily and * other static methods for working with Sets. * */ public class Sets { /** * Creates an empty {@code HashSet} instance. * * <p><b>Note:</b> if {@code E} is an {@link Enum} type, use {@link * EnumSet#noneOf} instead. * * <p><b>Note:</b> if you only need an <i>immutable</i> empty Set, * use {@link Collections#emptySet} instead. * * @return a newly-created, initially-empty {@code HashSet} */ public static <K> HashSet<K> newHashSet() { return new HashSet<K>(); } /** * Creates a {@code HashSet} instance containing the given elements. * * <p><b>Note:</b> due to a bug in javac 1.5.0_06, we cannot support the * following: * * <p>{@code Set<Base> set = Sets.newHashSet(sub1, sub2);} * * <p>where {@code sub1} and {@code sub2} are references to subtypes of {@code * Base}, not of {@code Base} itself. To get around this, you must use: * * <p>{@code Set<Base> set = Sets.<Base>newHashSet(sub1, sub2);} * * @param elements the elements that the set should contain * @return a newly-created {@code HashSet} containing those elements (minus * duplicates) */ public static <E> HashSet<E> newHashSet(E... elements) { int capacity = elements.length * 4 / 3 + 1; HashSet<E> set = new HashSet<E>(capacity); Collections.addAll(set, elements); return set; } /** * Creates a {@code SortedSet} instance containing the given elements. * * @param elements the elements that the set should contain * @return a newly-created {@code SortedSet} containing those elements (minus * duplicates) */ public static <E> SortedSet<E> newSortedSet(E... elements) { SortedSet<E> set = new TreeSet<E>(); Collections.addAll(set, elements); return set; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.CONTENT; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.UPDATED; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.END_TAG; import static org.xmlpull.v1.XmlPullParser.START_TAG; import static org.xmlpull.v1.XmlPullParser.TEXT; public class SpreadsheetEntry extends HashMap<String, String> { private static final Pattern sContentPattern = Pattern.compile( "(?:^|, )([_a-zA-Z0-9]+): (.*?)(?=\\s*$|, [_a-zA-Z0-9]+: )", Pattern.DOTALL); private static Matcher sContentMatcher; private static Matcher getContentMatcher(CharSequence input) { if (sContentMatcher == null) { sContentMatcher = sContentPattern.matcher(input); } else { sContentMatcher.reset(input); } return sContentMatcher; } private long mUpdated; public long getUpdated() { return mUpdated; } public static SpreadsheetEntry fromParser(XmlPullParser parser) throws XmlPullParserException, IOException { final int depth = parser.getDepth(); final SpreadsheetEntry entry = new SpreadsheetEntry(); String tag = null; int type; while (((type = parser.next()) != END_TAG || parser.getDepth() > depth) && type != END_DOCUMENT) { if (type == START_TAG) { tag = parser.getName(); } else if (type == END_TAG) { tag = null; } else if (type == TEXT) { if (UPDATED.equals(tag)) { final String text = parser.getText(); entry.mUpdated = ParserUtils.parseTime(text); } else if (CONTENT.equals(tag)) { final String text = parser.getText(); final Matcher matcher = getContentMatcher(text); while (matcher.find()) { final String key = matcher.group(1); final String value = matcher.group(2).trim(); entry.put(key, value); } } } } return entry; } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import android.content.AsyncQueryHandler; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import java.lang.ref.WeakReference; /** * Slightly more abstract {@link AsyncQueryHandler} that helps keep a * {@link WeakReference} back to a listener. Will properly close any * {@link Cursor} if the listener ceases to exist. * <p> * This pattern can be used to perform background queries without leaking * {@link Context} objects. * * @hide pending API council review */ public class NotifyingAsyncQueryHandler extends AsyncQueryHandler { private WeakReference<AsyncQueryListener> mListener; /** * Interface to listen for completed query operations. */ public interface AsyncQueryListener { void onQueryComplete(int token, Object cookie, Cursor cursor); } public NotifyingAsyncQueryHandler(ContentResolver resolver, AsyncQueryListener listener) { super(resolver); setQueryListener(listener); } /** * Assign the given {@link AsyncQueryListener} to receive query events from * asynchronous calls. Will replace any existing listener. */ public void setQueryListener(AsyncQueryListener listener) { mListener = new WeakReference<AsyncQueryListener>(listener); } /** * Clear any {@link AsyncQueryListener} set through * {@link #setQueryListener(AsyncQueryListener)} */ public void clearQueryListener() { mListener = null; } /** * Begin an asynchronous query with the given arguments. When finished, * {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} is * called if a valid {@link AsyncQueryListener} is present. */ public void startQuery(Uri uri, String[] projection) { startQuery(-1, null, uri, projection, null, null, null); } /** * Begin an asynchronous query with the given arguments. When finished, * {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} is called * if a valid {@link AsyncQueryListener} is present. * * @param token Unique identifier passed through to * {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} */ public void startQuery(int token, Uri uri, String[] projection) { startQuery(token, null, uri, projection, null, null, null); } /** * Begin an asynchronous query with the given arguments. When finished, * {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} is called * if a valid {@link AsyncQueryListener} is present. */ public void startQuery(Uri uri, String[] projection, String sortOrder) { startQuery(-1, null, uri, projection, null, null, sortOrder); } /** * Begin an asynchronous query with the given arguments. When finished, * {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} is called * if a valid {@link AsyncQueryListener} is present. */ public void startQuery(Uri uri, String[] projection, String selection, String[] selectionArgs, String orderBy) { startQuery(-1, null, uri, projection, selection, selectionArgs, orderBy); } /** * Begin an asynchronous update with the given arguments. */ public void startUpdate(Uri uri, ContentValues values) { startUpdate(-1, null, uri, values, null, null); } public void startInsert(Uri uri, ContentValues values) { startInsert(-1, null, uri, values); } public void startDelete(Uri uri) { startDelete(-1, null, uri, null, null); } /** {@inheritDoc} */ @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { final AsyncQueryListener listener = mListener == null ? null : mListener.get(); if (listener != null) { listener.onQueryComplete(token, cookie, cursor); } else if (cursor != null) { cursor.close(); } } }
Java
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import java.util.HashMap; import java.util.LinkedHashMap; /** * Provides static methods for creating mutable {@code Maps} instances easily. */ public class Maps { /** * Creates a {@code HashMap} instance. * * @return a newly-created, initially-empty {@code HashMap} */ public static <K, V> HashMap<K, V> newHashMap() { return new HashMap<K, V>(); } /** * Creates a {@code LinkedHashMap} instance. * * @return a newly-created, initially-empty {@code HashMap} */ public static <K, V> LinkedHashMap<K, V> newLinkedHashMap() { return new LinkedHashMap<K, V>(); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import com.google.android.apps.iosched.io.XmlHandler; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Tracks; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import android.content.ContentProvider; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.database.Cursor; import android.net.Uri; import android.text.format.Time; import java.io.InputStream; import java.util.ArrayList; import java.util.Set; import java.util.regex.Pattern; /** * Various utility methods used by {@link XmlHandler} implementations. */ public class ParserUtils { // TODO: consider refactor to HandlerUtils? // TODO: localize this string at some point public static final String BLOCK_TITLE_BREAKOUT_SESSIONS = "Breakout sessions"; public static final String BLOCK_TYPE_FOOD = "food"; public static final String BLOCK_TYPE_SESSION = "session"; public static final String BLOCK_TYPE_OFFICE_HOURS = "officehours"; // TODO: factor this out into a separate data file. public static final Set<String> LOCAL_TRACK_IDS = Sets.newHashSet( "accessibility", "android", "appengine", "chrome", "commerce", "developertools", "gamedevelopment", "geo", "googleapis", "googleapps", "googletv", "techtalk", "webgames", "youtube"); /** Used to sanitize a string to be {@link Uri} safe. */ private static final Pattern sSanitizePattern = Pattern.compile("[^a-z0-9-_]"); private static final Pattern sParenPattern = Pattern.compile("\\(.*?\\)"); /** Used to split a comma-separated string. */ private static final Pattern sCommaPattern = Pattern.compile("\\s*,\\s*"); private static Time sTime = new Time(); private static XmlPullParserFactory sFactory; /** * Sanitize the given string to be {@link Uri} safe for building * {@link ContentProvider} paths. */ public static String sanitizeId(String input) { return sanitizeId(input, false); } /** * Sanitize the given string to be {@link Uri} safe for building * {@link ContentProvider} paths. */ public static String sanitizeId(String input, boolean stripParen) { if (input == null) return null; if (stripParen) { // Strip out all parenthetical statements when requested. input = sParenPattern.matcher(input).replaceAll(""); } return sSanitizePattern.matcher(input.toLowerCase()).replaceAll(""); } /** * Split the given comma-separated string, returning all values. */ public static String[] splitComma(CharSequence input) { if (input == null) return new String[0]; return sCommaPattern.split(input); } /** * Build and return a new {@link XmlPullParser} with the given * {@link InputStream} assigned to it. */ public static XmlPullParser newPullParser(InputStream input) throws XmlPullParserException { if (sFactory == null) { sFactory = XmlPullParserFactory.newInstance(); } final XmlPullParser parser = sFactory.newPullParser(); parser.setInput(input, null); return parser; } /** * Parse the given string as a RFC 3339 timestamp, returning the value as * milliseconds since the epoch. */ public static long parseTime(String time) { sTime.parse3339(time); return sTime.toMillis(false); } /** * Return a {@link Blocks#BLOCK_ID} matching the requested arguments. */ public static String findBlock(String title, long startTime, long endTime) { // TODO: in future we might check provider if block exists return Blocks.generateBlockId(startTime, endTime); } /** * Return a {@link Blocks#BLOCK_ID} matching the requested arguments, * inserting a new {@link Blocks} entry as a * {@link ContentProviderOperation} when none already exists. */ public static String findOrCreateBlock(String title, String type, long startTime, long endTime, ArrayList<ContentProviderOperation> batch, ContentResolver resolver) { // TODO: check for existence instead of always blindly creating. it's // okay for now since the database replaces on conflict. final ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Blocks.CONTENT_URI); final String blockId = Blocks.generateBlockId(startTime, endTime); builder.withValue(Blocks.BLOCK_ID, blockId); builder.withValue(Blocks.BLOCK_TITLE, title); builder.withValue(Blocks.BLOCK_START, startTime); builder.withValue(Blocks.BLOCK_END, endTime); builder.withValue(Blocks.BLOCK_TYPE, type); batch.add(builder.build()); return blockId; } /** * Query and return the {@link SyncColumns#UPDATED} time for the requested * {@link Uri}. Expects the {@link Uri} to reference a single item. */ public static long queryItemUpdated(Uri uri, ContentResolver resolver) { final String[] projection = { SyncColumns.UPDATED }; final Cursor cursor = resolver.query(uri, projection, null, null, null); try { if (cursor.moveToFirst()) { return cursor.getLong(0); } else { return ScheduleContract.UPDATED_NEVER; } } finally { cursor.close(); } } /** * Query and return the newest {@link SyncColumns#UPDATED} time for all * entries under the requested {@link Uri}. Expects the {@link Uri} to * reference a directory of several items. */ public static long queryDirUpdated(Uri uri, ContentResolver resolver) { final String[] projection = { "MAX(" + SyncColumns.UPDATED + ")" }; final Cursor cursor = resolver.query(uri, projection, null, null, null); try { cursor.moveToFirst(); return cursor.getLong(0); } finally { cursor.close(); } } /** * Translate an incoming {@link Tracks#TRACK_ID}, usually passing directly * through, but returning a different value when a local alias is defined. */ public static String translateTrackIdAlias(String trackId) { //if ("gwt".equals(trackId)) { // return "googlewebtoolkit"; //} else { return trackId; //} } /** * Translate a possibly locally aliased {@link Tracks#TRACK_ID} to its real value; * this usually is a pass-through. */ public static String translateTrackIdAliasInverse(String trackId) { //if ("googlewebtoolkit".equals(trackId)) { // return "gwt"; //} else { return trackId; //} } /** XML tag constants used by the Atom standard. */ public interface AtomTags { String ENTRY = "entry"; String UPDATED = "updated"; String TITLE = "title"; String LINK = "link"; String CONTENT = "content"; String REL = "rel"; String HREF = "href"; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import android.graphics.Rect; import android.graphics.RectF; import android.view.MotionEvent; import android.view.TouchDelegate; import android.view.View; /** * {@link TouchDelegate} that gates {@link MotionEvent} instances by comparing * then against fractional dimensions of the source view. * <p> * This is particularly useful when you want to define a rectangle in terms of * the source dimensions, but when those dimensions might change due to pending * or future layout passes. * <p> * One example is catching touches that occur in the top-right quadrant of * {@code sourceParent}, and relaying them to {@code targetChild}. This could be * done with: <code> * FractionalTouchDelegate.setupDelegate(sourceParent, targetChild, new RectF(0.5f, 0f, 1f, 0.5f)); * </code> */ public class FractionalTouchDelegate extends TouchDelegate { private View mSource; private View mTarget; private RectF mSourceFraction; private Rect mScrap = new Rect(); /** Cached full dimensions of {@link #mSource}. */ private Rect mSourceFull = new Rect(); /** Cached projection of {@link #mSourceFraction} onto {@link #mSource}. */ private Rect mSourcePartial = new Rect(); private boolean mDelegateTargeted; public FractionalTouchDelegate(View source, View target, RectF sourceFraction) { super(new Rect(0, 0, 0, 0), target); mSource = source; mTarget = target; mSourceFraction = sourceFraction; } /** * Helper to create and setup a {@link FractionalTouchDelegate} between the * given {@link View}. * * @param source Larger source {@link View}, usually a parent, that will be * assigned {@link View#setTouchDelegate(TouchDelegate)}. * @param target Smaller target {@link View} which will receive * {@link MotionEvent} that land in requested fractional area. * @param sourceFraction Fractional area projected onto source {@link View} * which determines when {@link MotionEvent} will be passed to * target {@link View}. */ public static void setupDelegate(View source, View target, RectF sourceFraction) { source.setTouchDelegate(new FractionalTouchDelegate(source, target, sourceFraction)); } /** * Consider updating {@link #mSourcePartial} when {@link #mSource} * dimensions have changed. */ private void updateSourcePartial() { mSource.getHitRect(mScrap); if (!mScrap.equals(mSourceFull)) { // Copy over and calculate fractional rectangle mSourceFull.set(mScrap); final int width = mSourceFull.width(); final int height = mSourceFull.height(); mSourcePartial.left = (int) (mSourceFraction.left * width); mSourcePartial.top = (int) (mSourceFraction.top * height); mSourcePartial.right = (int) (mSourceFraction.right * width); mSourcePartial.bottom = (int) (mSourceFraction.bottom * height); } } @Override public boolean onTouchEvent(MotionEvent event) { updateSourcePartial(); // The logic below is mostly copied from the parent class, since we // can't update private mBounds variable. // http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob; // f=core/java/android/view/TouchDelegate.java;hb=eclair#l98 final Rect sourcePartial = mSourcePartial; final View target = mTarget; int x = (int)event.getX(); int y = (int)event.getY(); boolean sendToDelegate = false; boolean hit = true; boolean handled = false; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if (sourcePartial.contains(x, y)) { mDelegateTargeted = true; sendToDelegate = true; } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_MOVE: sendToDelegate = mDelegateTargeted; if (sendToDelegate) { if (!sourcePartial.contains(x, y)) { hit = false; } } break; case MotionEvent.ACTION_CANCEL: sendToDelegate = mDelegateTargeted; mDelegateTargeted = false; break; } if (sendToDelegate) { if (hit) { event.setLocation(target.getWidth() / 2, target.getHeight() / 2); } else { event.setLocation(-1, -1); } handled = target.dispatchTouchEvent(event); } return handled; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import android.os.Bundle; import android.os.Handler; import android.os.ResultReceiver; import android.util.Log; /** * Proxy {@link ResultReceiver} that offers a listener interface that can be * detached. Useful for when sending callbacks to a {@link Service} where a * listening {@link Activity} can be swapped out during configuration changes. */ public class DetachableResultReceiver extends ResultReceiver { private static final String TAG = "DetachableResultReceiver"; private Receiver mReceiver; public DetachableResultReceiver(Handler handler) { super(handler); } public void clearReceiver() { mReceiver = null; } public void setReceiver(Receiver receiver) { mReceiver = receiver; } public interface Receiver { public void onReceiveResult(int resultCode, Bundle resultData); } @Override protected void onReceiveResult(int resultCode, Bundle resultData) { if (mReceiver != null) { mReceiver.onReceiveResult(resultCode, resultData); } else { Log.w(TAG, "Dropping result on floor for code " + resultCode + ": " + resultData.toString()); } } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import com.google.android.apps.iosched.R; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.AsyncTask; import android.preference.PreferenceManager; /** * A helper for showing EULAs and storing a {@link SharedPreferences} bit indicating whether the * user has accepted. */ public class EulaHelper { public static boolean hasAcceptedEula(final Context context) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); return sp.getBoolean("accepted_eula", false); } private static void setAcceptedEula(final Context context) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); sp.edit().putBoolean("accepted_eula", true).commit(); return null; } }.execute(); } /** * Show End User License Agreement. * * @param accepted True IFF user has accepted license already, which means it can be dismissed. * If the user hasn't accepted, then the EULA must be accepted or the program * exits. * @param activity Activity started from. */ public static void showEula(final boolean accepted, final Activity activity) { AlertDialog.Builder eula = new AlertDialog.Builder(activity) .setTitle(R.string.eula_title) .setIcon(android.R.drawable.ic_dialog_info) .setMessage(R.string.eula_text) .setCancelable(accepted); if (accepted) { // If they've accepted the EULA allow, show an OK to dismiss. eula.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); } else { // If they haven't accepted the EULA allow, show accept/decline buttons and exit on // decline. eula .setPositiveButton(R.string.accept, new android.content.DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { setAcceptedEula(activity); dialog.dismiss(); } }) .setNegativeButton(R.string.decline, new android.content.DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); activity.finish(); } }); } eula.show(); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import com.google.android.apps.iosched.R; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; /** * Helper class for the Catch Notes integration, based on example code at * {@link https://github.com/catch/docs-api/}. */ public class CatchNotesHelper { private static final String TAG = "CatchNotesHelper"; // Intent actions public static final String ACTION_ADD = "com.catchnotes.intent.action.ADD"; public static final String ACTION_VIEW = "com.catchnotes.intent.action.VIEW"; // Intent extras for ACTION_ADD public static final String EXTRA_SOURCE = "com.catchnotes.intent.extra.SOURCE"; public static final String EXTRA_SOURCE_URL = "com.catchnotes.intent.extra.SOURCE_URL"; // Intent extras for ACTION_VIEW public static final String EXTRA_VIEW_FILTER = "com.catchnotes.intent.extra.VIEW_FILTER"; // Note: "3banana" was the original name of Catch Notes. Though it has been // rebranded, the package name must persist. private static final String NOTES_PACKAGE_NAME = "com.threebanana.notes"; private static final String NOTES_MARKET_URI = "http://market.android.com/details?id=" + NOTES_PACKAGE_NAME; private static final int NOTES_MIN_VERSION_CODE = 54; private final Context mContext; public CatchNotesHelper(Context context) { mContext = context; } public Intent createNoteIntent(String message) { if (!isNotesInstalledAndMinimumVersion()) { return notesMarketIntent(); } Intent intent = new Intent(); intent.setAction(ACTION_ADD); intent.putExtra(Intent.EXTRA_TEXT, message); intent.putExtra(EXTRA_SOURCE, mContext.getString(R.string.app_name)); intent.putExtra(EXTRA_SOURCE_URL, "http://www.google.com/io/"); intent.putExtra(Intent.EXTRA_TITLE, mContext.getString(R.string.app_name)); return intent; } public Intent viewNotesIntent(String tag) { if (!isNotesInstalledAndMinimumVersion()) { return notesMarketIntent(); } if (!tag.startsWith("#")) { tag = "#" + tag; } Intent intent = new Intent(); intent.setAction(ACTION_VIEW); intent.putExtra(EXTRA_VIEW_FILTER, tag); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); return intent; } /** * Returns the installation status of Catch Notes. */ public boolean isNotesInstalledAndMinimumVersion() { try { PackageInfo packageInfo = mContext.getPackageManager() .getPackageInfo(NOTES_PACKAGE_NAME, PackageManager.GET_ACTIVITIES); if (packageInfo.versionCode < NOTES_MIN_VERSION_CODE) { return false; } } catch (NameNotFoundException e) { return false; } return true; } public Intent notesMarketIntent() { Uri uri = Uri.parse(NOTES_MARKET_URI); Intent intent = new Intent(Intent.ACTION_VIEW, uri); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); return intent; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import com.google.android.apps.iosched.R; import android.app.ActionBar; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; /** * An extension of {@link ActivityHelper} that provides Android 3.0-specific functionality for * Honeycomb tablets. It thus requires API level 11. */ public class ActivityHelperHoneycomb extends ActivityHelper { private Menu mOptionsMenu; protected ActivityHelperHoneycomb(Activity activity) { super(activity); } @Override public void onPostCreate(Bundle savedInstanceState) { // Do nothing in onPostCreate. ActivityHelper creates the old action bar, we don't // need to for Honeycomb. } @Override public boolean onCreateOptionsMenu(Menu menu) { mOptionsMenu = menu; return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // Handle the HOME / UP affordance. Since the app is only two levels deep // hierarchically, UP always just goes home. goHome(); return true; } return super.onOptionsItemSelected(item); } /** {@inheritDoc} */ @Override public void setupHomeActivity() { super.setupHomeActivity(); // NOTE: there needs to be a content view set before this is called, so this method // should be called in onPostCreate. if (UIUtils.isTablet(mActivity)) { mActivity.getActionBar().setDisplayOptions( 0, ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE); } else { mActivity.getActionBar().setDisplayOptions( ActionBar.DISPLAY_USE_LOGO, ActionBar.DISPLAY_USE_LOGO | ActionBar.DISPLAY_SHOW_TITLE); } } /** {@inheritDoc} */ @Override public void setupSubActivity() { super.setupSubActivity(); // NOTE: there needs to be a content view set before this is called, so this method // should be called in onPostCreate. if (UIUtils.isTablet(mActivity)) { mActivity.getActionBar().setDisplayOptions( ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_USE_LOGO, ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_USE_LOGO); } else { mActivity.getActionBar().setDisplayOptions( 0, ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_USE_LOGO); } } /** * No-op on Honeycomb. The action bar title always remains the same. */ @Override public void setActionBarTitle(CharSequence title) { } /** * No-op on Honeycomb. The action bar color always remains the same. */ @Override public void setActionBarColor(int color) { if (!UIUtils.isTablet(mActivity)) { super.setActionBarColor(color); } } /** {@inheritDoc} */ @Override public void setRefreshActionButtonCompatState(boolean refreshing) { // On Honeycomb, we can set the state of the refresh button by giving it a custom // action view. if (mOptionsMenu == null) { return; } final MenuItem refreshItem = mOptionsMenu.findItem(R.id.menu_refresh); if (refreshItem != null) { if (refreshing) { refreshItem.setActionView(R.layout.actionbar_indeterminate_progress); } else { refreshItem.setActionView(null); } } } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Tracks; import com.google.android.apps.iosched.util.Lists; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.graphics.Color; import java.io.IOException; import java.util.ArrayList; import static com.google.android.apps.iosched.util.ParserUtils.sanitizeId; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.END_TAG; import static org.xmlpull.v1.XmlPullParser.START_TAG; import static org.xmlpull.v1.XmlPullParser.TEXT; public class LocalTracksHandler extends XmlHandler { public LocalTracksHandler() { super(ScheduleContract.CONTENT_AUTHORITY); } @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); batch.add(ContentProviderOperation.newDelete(Tracks.CONTENT_URI).build()); int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG && Tags.TRACK.equals(parser.getName())) { batch.add(parseTrack(parser)); } } return batch; } private static ContentProviderOperation parseTrack(XmlPullParser parser) throws XmlPullParserException, IOException { final int depth = parser.getDepth(); final ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Tracks.CONTENT_URI); String tag = null; int type; while (((type = parser.next()) != END_TAG || parser.getDepth() > depth) && type != END_DOCUMENT) { if (type == START_TAG) { tag = parser.getName(); } else if (type == END_TAG) { tag = null; } else if (type == TEXT) { final String text = parser.getText(); if (Tags.NAME.equals(tag)) { final String trackId = sanitizeId(text); builder.withValue(Tracks.TRACK_ID, trackId); builder.withValue(Tracks.TRACK_NAME, text); } else if (Tags.COLOR.equals(tag)) { final int color = Color.parseColor(text); builder.withValue(Tracks.TRACK_COLOR, color); } else if (Tags.ABSTRACT.equals(tag)) { builder.withValue(Tracks.TRACK_ABSTRACT, text); } } } return builder.build(); } interface Tags { String TRACK = "track"; String NAME = "name"; String COLOR = "color"; String ABSTRACT = "abstract"; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Speakers; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.SpreadsheetEntry; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.net.Uri; import android.util.Log; import java.io.IOException; import java.util.ArrayList; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.ENTRY; import static com.google.android.apps.iosched.util.ParserUtils.queryItemUpdated; import static com.google.android.apps.iosched.util.ParserUtils.sanitizeId; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.START_TAG; /** * Handle a remote {@link XmlPullParser} that defines a set of {@link Speakers} * entries. Assumes that the remote source is a Google Spreadsheet. */ public class RemoteSpeakersHandler extends XmlHandler { private static final String TAG = "SpeakersHandler"; public RemoteSpeakersHandler() { super(ScheduleContract.CONTENT_AUTHORITY); } /** {@inheritDoc} */ @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); // Walk document, parsing any incoming entries int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG && ENTRY.equals(parser.getName())) { // Process single spreadsheet row at a time final SpreadsheetEntry entry = SpreadsheetEntry.fromParser(parser); final String speakerId = sanitizeId(entry.get(Columns.SPEAKER_TITLE), true); final Uri speakerUri = Speakers.buildSpeakerUri(speakerId); // Check for existing details, only update when changed final long localUpdated = queryItemUpdated(speakerUri, resolver); final long serverUpdated = entry.getUpdated(); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "found speaker " + entry.toString()); Log.v(TAG, "found localUpdated=" + localUpdated + ", server=" + serverUpdated); } if (localUpdated >= serverUpdated) continue; // Clear any existing values for this speaker, treating the // incoming details as authoritative. batch.add(ContentProviderOperation.newDelete(speakerUri).build()); final ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Speakers.CONTENT_URI); builder.withValue(SyncColumns.UPDATED, serverUpdated); builder.withValue(Speakers.SPEAKER_ID, speakerId); builder.withValue(Speakers.SPEAKER_NAME, entry.get(Columns.SPEAKER_TITLE)); builder.withValue(Speakers.SPEAKER_IMAGE_URL, entry.get(Columns.SPEAKER_IMAGE_URL)); builder.withValue(Speakers.SPEAKER_COMPANY, entry.get(Columns.SPEAKER_COMPANY)); builder.withValue(Speakers.SPEAKER_ABSTRACT, entry.get(Columns.SPEAKER_ABSTRACT)); builder.withValue(Speakers.SPEAKER_URL, entry.get(Columns.SPEAKER_URL)); // Normal speaker details ready, write to provider batch.add(builder.build()); } } return batch; } /** Columns coming from remote spreadsheet. */ private interface Columns { String SPEAKER_TITLE = "speakertitle"; String SPEAKER_IMAGE_URL = "speakerimageurl"; String SPEAKER_COMPANY = "speakercompany"; String SPEAKER_ABSTRACT = "speakerabstract"; String SPEAKER_URL = "speakerurl"; // speaker_title: Aaron Koblin // speaker_image_url: http://path/to/image.png // speaker_company: Google // speaker_abstract: Aaron takes social and infrastructural data and uses... // speaker_url: http://profiles.google.com/... } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Vendors; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.ParserUtils; import com.google.android.apps.iosched.util.SpreadsheetEntry; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.util.Log; import java.io.IOException; import java.util.ArrayList; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.ENTRY; import static com.google.android.apps.iosched.util.ParserUtils.sanitizeId; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.START_TAG; /** * Handle a remote {@link XmlPullParser} that defines a set of {@link Vendors} * entries. Assumes that the remote source is a Google Spreadsheet. */ public class RemoteVendorsHandler extends XmlHandler { private static final String TAG = "VendorsHandler"; public RemoteVendorsHandler() { super(ScheduleContract.CONTENT_AUTHORITY); } /** {@inheritDoc} */ @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); // Walk document, parsing any incoming entries int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG && ENTRY.equals(parser.getName())) { // Process single spreadsheet row at a time final SpreadsheetEntry entry = SpreadsheetEntry.fromParser(parser); final String vendorId = sanitizeId(entry.get(Columns.COMPANY_NAME)); final Uri vendorUri = Vendors.buildVendorUri(vendorId); // Check for existing details, only update when changed final ContentValues values = queryVendorDetails(vendorUri, resolver); final long localUpdated = values.getAsLong(SyncColumns.UPDATED); final long serverUpdated = entry.getUpdated(); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "found vendor " + entry.toString()); Log.v(TAG, "found localUpdated=" + localUpdated + ", server=" + serverUpdated); } if (localUpdated >= serverUpdated) continue; // Clear any existing values for this vendor, treating the // incoming details as authoritative. batch.add(ContentProviderOperation.newDelete(vendorUri).build()); final ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Vendors.CONTENT_URI); builder.withValue(SyncColumns.UPDATED, serverUpdated); builder.withValue(Vendors.VENDOR_ID, vendorId); builder.withValue(Vendors.VENDOR_NAME, entry.get(Columns.COMPANY_NAME)); builder.withValue(Vendors.VENDOR_LOCATION, entry.get(Columns.COMPANY_LOCATION)); builder.withValue(Vendors.VENDOR_DESC, entry.get(Columns.COMPANY_DESC)); builder.withValue(Vendors.VENDOR_URL, entry.get(Columns.COMPANY_URL)); builder.withValue(Vendors.VENDOR_LOGO_URL, entry.get(Columns.COMPANY_LOGO)); builder.withValue(Vendors.VENDOR_PRODUCT_DESC, entry.get(Columns.COMPANY_PRODUCT_DESC)); // Inherit starred value from previous row if (values.containsKey(Vendors.VENDOR_STARRED)) { builder.withValue(Vendors.VENDOR_STARRED, values.getAsInteger(Vendors.VENDOR_STARRED)); } // Assign track final String trackId = ParserUtils.translateTrackIdAlias(sanitizeId(entry .get(Columns.COMPANY_POD))); builder.withValue(Vendors.TRACK_ID, trackId); // Normal vendor details ready, write to provider batch.add(builder.build()); } } return batch; } private static ContentValues queryVendorDetails(Uri uri, ContentResolver resolver) { final ContentValues values = new ContentValues(); final Cursor cursor = resolver.query(uri, VendorsQuery.PROJECTION, null, null, null); try { if (cursor.moveToFirst()) { values.put(SyncColumns.UPDATED, cursor.getLong(VendorsQuery.UPDATED)); values.put(Vendors.VENDOR_STARRED, cursor.getInt(VendorsQuery.STARRED)); } else { values.put(SyncColumns.UPDATED, ScheduleContract.UPDATED_NEVER); } } finally { cursor.close(); } return values; } private interface VendorsQuery { String[] PROJECTION = { SyncColumns.UPDATED, Vendors.VENDOR_STARRED, }; int UPDATED = 0; int STARRED = 1; } /** Columns coming from remote spreadsheet. */ private interface Columns { String COMPANY_NAME = "companyname"; String COMPANY_LOCATION = "companylocation"; String COMPANY_DESC = "companydesc"; String COMPANY_URL = "companyurl"; String COMPANY_PRODUCT_DESC = "companyproductdesc"; String COMPANY_LOGO = "companylogo"; String COMPANY_POD = "companypod"; // company_name: 280 North, Inc. // company_location: San Francisco, California // company_desc: Creators of 280 Slides, a web based presentation // company_url: www.280north.com // company_product_desc: 280 Slides relies on the Google AJAX APIs to provide // company_logo: 280north.png // company_pod: Google APIs // company_tags: } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.SearchSuggest; import com.google.android.apps.iosched.util.Lists; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.app.SearchManager; import android.content.ContentProviderOperation; import android.content.ContentResolver; import java.io.IOException; import java.util.ArrayList; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.END_TAG; import static org.xmlpull.v1.XmlPullParser.START_TAG; import static org.xmlpull.v1.XmlPullParser.TEXT; public class LocalSearchSuggestHandler extends XmlHandler { public LocalSearchSuggestHandler() { super(ScheduleContract.CONTENT_AUTHORITY); } @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); // Clear any existing suggestion words batch.add(ContentProviderOperation.newDelete(SearchSuggest.CONTENT_URI).build()); String tag = null; int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG) { tag = parser.getName(); } else if (type == END_TAG) { tag = null; } else if (type == TEXT) { final String text = parser.getText(); if (Tags.WORD.equals(tag)) { // Insert word as search suggestion batch.add(ContentProviderOperation.newInsert(SearchSuggest.CONTENT_URI) .withValue(SearchManager.SUGGEST_COLUMN_TEXT_1, text).build()); } } } return batch; } private interface Tags { String WORD = "word"; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Rooms; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.Tracks; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsTracks; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.ParserUtils; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.database.Cursor; import android.net.Uri; import java.io.IOException; import java.util.ArrayList; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.END_TAG; import static org.xmlpull.v1.XmlPullParser.START_TAG; import static org.xmlpull.v1.XmlPullParser.TEXT; public class LocalSessionsHandler extends XmlHandler { public LocalSessionsHandler() { super(ScheduleContract.CONTENT_AUTHORITY); } @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG && Tags.SESSION.equals(parser.getName())) { parseSession(parser, batch, resolver); } } return batch; } private static void parseSession(XmlPullParser parser, ArrayList<ContentProviderOperation> batch, ContentResolver resolver) throws XmlPullParserException, IOException { final int depth = parser.getDepth(); ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Sessions.CONTENT_URI); builder.withValue(Sessions.UPDATED, 0); long startTime = -1; long endTime = -1; String title = null; String sessionId = null; String trackId = null; String tag = null; int type; while (((type = parser.next()) != END_TAG || parser.getDepth() > depth) && type != END_DOCUMENT) { if (type == START_TAG) { tag = parser.getName(); } else if (type == END_TAG) { tag = null; } else if (type == TEXT) { final String text = parser.getText(); if (Tags.START.equals(tag)) { startTime = ParserUtils.parseTime(text); } else if (Tags.END.equals(tag)) { endTime = ParserUtils.parseTime(text); } else if (Tags.ROOM.equals(tag)) { final String roomId = Rooms.generateRoomId(text); builder.withValue(Sessions.ROOM_ID, roomId); } else if (Tags.TRACK.equals(tag)) { trackId = Tracks.generateTrackId(text); } else if (Tags.ID.equals(tag)) { sessionId = text; } else if (Tags.TITLE.equals(tag)) { title = text; } else if (Tags.ABSTRACT.equals(tag)) { builder.withValue(Sessions.SESSION_ABSTRACT, text); } } } if (sessionId == null) { sessionId = Sessions.generateSessionId(title); } builder.withValue(Sessions.SESSION_ID, sessionId); builder.withValue(Sessions.SESSION_TITLE, title); // Use empty strings to make sure SQLite search trigger has valid data // for updating search index. builder.withValue(Sessions.SESSION_ABSTRACT, ""); builder.withValue(Sessions.SESSION_REQUIREMENTS, ""); builder.withValue(Sessions.SESSION_KEYWORDS, ""); final String blockId = ParserUtils.findBlock(title, startTime, endTime); builder.withValue(Sessions.BLOCK_ID, blockId); // Propagate any existing starred value final Uri sessionUri = Sessions.buildSessionUri(sessionId); final int starred = querySessionStarred(sessionUri, resolver); if (starred != -1) { builder.withValue(Sessions.SESSION_STARRED, starred); } batch.add(builder.build()); if (trackId != null) { // TODO: support parsing multiple tracks per session final Uri sessionTracks = Sessions.buildTracksDirUri(sessionId); batch.add(ContentProviderOperation.newInsert(sessionTracks) .withValue(SessionsTracks.SESSION_ID, sessionId) .withValue(SessionsTracks.TRACK_ID, trackId).build()); } } public static int querySessionStarred(Uri uri, ContentResolver resolver) { final String[] projection = { Sessions.SESSION_STARRED }; final Cursor cursor = resolver.query(uri, projection, null, null, null); try { if (cursor.moveToFirst()) { return cursor.getInt(0); } else { return -1; } } finally { cursor.close(); } } interface Tags { String SESSION = "session"; String ID = "id"; String START = "start"; String END = "end"; String ROOM = "room"; String TRACK = "track"; String TITLE = "title"; String ABSTRACT = "abstract"; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProvider; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.content.OperationApplicationException; import android.os.RemoteException; import java.io.IOException; import java.util.ArrayList; /** * Abstract class that handles reading and parsing an {@link XmlPullParser} into * a set of {@link ContentProviderOperation}. It catches recoverable network * exceptions and rethrows them as {@link HandlerException}. Any local * {@link ContentProvider} exceptions are considered unrecoverable. * <p> * This class is only designed to handle simple one-way synchronization. */ public abstract class XmlHandler { private final String mAuthority; public XmlHandler(String authority) { mAuthority = authority; } /** * Parse the given {@link XmlPullParser}, turning into a series of * {@link ContentProviderOperation} that are immediately applied using the * given {@link ContentResolver}. */ public void parseAndApply(XmlPullParser parser, ContentResolver resolver) throws HandlerException { try { final ArrayList<ContentProviderOperation> batch = parse(parser, resolver); resolver.applyBatch(mAuthority, batch); } catch (HandlerException e) { throw e; } catch (XmlPullParserException e) { throw new HandlerException("Problem parsing XML response", e); } catch (IOException e) { throw new HandlerException("Problem reading response", e); } catch (RemoteException e) { // Failed binder transactions aren't recoverable throw new RuntimeException("Problem applying batch operation", e); } catch (OperationApplicationException e) { // Failures like constraint violation aren't recoverable // TODO: write unit tests to exercise full provider // TODO: consider catching version checking asserts here, and then // wrapping around to retry parsing again. throw new RuntimeException("Problem applying batch operation", e); } } /** * Parse the given {@link XmlPullParser}, returning a set of * {@link ContentProviderOperation} that will bring the * {@link ContentProvider} into sync with the parsed data. */ public abstract ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException; /** * General {@link IOException} that indicates a problem occured while * parsing or applying an {@link XmlPullParser}. */ public static class HandlerException extends IOException { public HandlerException(String message) { super(message); } public HandlerException(String message, Throwable cause) { super(message); initCause(cause); } @Override public String toString() { if (getCause() != null) { return getLocalizedMessage() + ": " + getCause(); } else { return getLocalizedMessage(); } } } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Rooms; import com.google.android.apps.iosched.util.Lists; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProviderOperation; import android.content.ContentResolver; import java.io.IOException; import java.util.ArrayList; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.END_TAG; import static org.xmlpull.v1.XmlPullParser.START_TAG; import static org.xmlpull.v1.XmlPullParser.TEXT; /** * Handle a local {@link XmlPullParser} that defines a set of {@link Rooms} * entries. Usually loaded from {@link R.xml} resources. */ public class LocalRoomsHandler extends XmlHandler { public LocalRoomsHandler() { super(ScheduleContract.CONTENT_AUTHORITY); } /** {@inheritDoc} */ @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG && Tags.ROOM.equals(parser.getName())) { parseRoom(parser, batch, resolver); } } return batch; } /** * Parse a given {@link Rooms} entry, building * {@link ContentProviderOperation} to define it locally. */ private static void parseRoom(XmlPullParser parser, ArrayList<ContentProviderOperation> batch, ContentResolver resolver) throws XmlPullParserException, IOException { final int depth = parser.getDepth(); ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Rooms.CONTENT_URI); String tag = null; int type; while (((type = parser.next()) != END_TAG || parser.getDepth() > depth) && type != END_DOCUMENT) { if (type == START_TAG) { tag = parser.getName(); } else if (type == END_TAG) { tag = null; } else if (type == TEXT) { final String text = parser.getText(); if (Tags.ID.equals(tag)) { builder.withValue(Rooms.ROOM_ID, text); } else if (Tags.NAME.equals(tag)) { builder.withValue(Rooms.ROOM_NAME, text); } else if (Tags.FLOOR.equals(tag)) { builder.withValue(Rooms.ROOM_FLOOR, text); } } } batch.add(builder.build()); } /** XML tags expected from local source. */ private interface Tags { String ROOM = "room"; String ID = "id"; String NAME = "name"; String FLOOR = "floor"; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSpeakers; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsTracks; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.ParserUtils; import com.google.android.apps.iosched.util.SpreadsheetEntry; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.text.format.Time; import android.util.Log; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Locale; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.ENTRY; import static com.google.android.apps.iosched.util.ParserUtils.sanitizeId; import static com.google.android.apps.iosched.util.ParserUtils.splitComma; import static com.google.android.apps.iosched.util.ParserUtils.translateTrackIdAlias; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.START_TAG; /** * Handle a remote {@link XmlPullParser} that defines a set of {@link Sessions} * entries. Assumes that the remote source is a Google Spreadsheet. */ public class RemoteSessionsHandler extends XmlHandler { private static final String TAG = "SessionsHandler"; /** * Custom format used internally that matches expected concatenation of * {@link Columns#SESSION_DATE} and {@link Columns#SESSION_TIME}. */ private static final SimpleDateFormat sTimeFormat = new SimpleDateFormat( "EEEE MMM d yyyy h:mma Z", Locale.US); public RemoteSessionsHandler() { super(ScheduleContract.CONTENT_AUTHORITY); } /** {@inheritDoc} */ @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); // Walk document, parsing any incoming entries int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG && ENTRY.equals(parser.getName())) { // Process single spreadsheet row at a time final SpreadsheetEntry entry = SpreadsheetEntry.fromParser(parser); final String sessionId = sanitizeId(entry.get(Columns.SESSION_TITLE)); final Uri sessionUri = Sessions.buildSessionUri(sessionId); // Check for existing details, only update when changed final ContentValues values = querySessionDetails(sessionUri, resolver); final long localUpdated = values.getAsLong(SyncColumns.UPDATED); final long serverUpdated = entry.getUpdated(); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "found session " + entry.toString()); Log.v(TAG, "found localUpdated=" + localUpdated + ", server=" + serverUpdated); } if (localUpdated >= serverUpdated) continue; final Uri sessionTracksUri = Sessions.buildTracksDirUri(sessionId); final Uri sessionSpeakersUri = Sessions.buildSpeakersDirUri(sessionId); // Clear any existing values for this session, treating the // incoming details as authoritative. batch.add(ContentProviderOperation.newDelete(sessionUri).build()); batch.add(ContentProviderOperation.newDelete(sessionTracksUri).build()); batch.add(ContentProviderOperation.newDelete(sessionSpeakersUri).build()); final ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Sessions.CONTENT_URI); builder.withValue(SyncColumns.UPDATED, serverUpdated); builder.withValue(Sessions.SESSION_ID, sessionId); builder.withValue(Sessions.SESSION_LEVEL, entry.get(Columns.SESSION_LEVEL)); builder.withValue(Sessions.SESSION_TITLE, entry.get(Columns.SESSION_TITLE)); builder.withValue(Sessions.SESSION_ABSTRACT, entry.get(Columns.SESSION_ABSTRACT)); builder.withValue(Sessions.SESSION_REQUIREMENTS, entry.get(Columns.SESSION_REQUIREMENTS)); builder.withValue(Sessions.SESSION_KEYWORDS, entry.get(Columns.SESSION_TAGS)); builder.withValue(Sessions.SESSION_HASHTAG, entry.get(Columns.SESSION_HASHTAG)); builder.withValue(Sessions.SESSION_SLUG, entry.get(Columns.SESSION_SLUG)); builder.withValue(Sessions.SESSION_URL, entry.get(Columns.SESSION_URL)); builder.withValue(Sessions.SESSION_MODERATOR_URL, entry.get(Columns.SESSION_MODERATOR_URL)); builder.withValue(Sessions.SESSION_YOUTUBE_URL, entry.get(Columns.SESSION_YOUTUBE_URL)); builder.withValue(Sessions.SESSION_PDF_URL, entry.get(Columns.SESSION_PDF_URL)); builder.withValue(Sessions.SESSION_FEEDBACK_URL, entry.get(Columns.SESSION_FEEDBACK_URL)); builder.withValue(Sessions.SESSION_NOTES_URL, entry.get(Columns.SESSION_NOTES_URL)); // Inherit starred value from previous row if (values.containsKey(Sessions.SESSION_STARRED)) { builder.withValue(Sessions.SESSION_STARRED, values.getAsInteger(Sessions.SESSION_STARRED)); } // Parse time string from two columns, which is pretty ugly code // since it assumes the column format is "Wednesday May 19" and // "10:45am-11:45am". Future spreadsheets should use RFC 3339. final String date = entry.get(Columns.SESSION_DATE); final String time = entry.get(Columns.SESSION_TIME); final int timeSplit = time.indexOf("-"); if (timeSplit == -1) { throw new HandlerException("Expecting " + Columns.SESSION_TIME + " to express span"); } final long startTime = parseTime(date, time.substring(0, timeSplit)); final long endTime = parseTime(date, time.substring(timeSplit + 1)); final String blockId = ParserUtils.findOrCreateBlock( ParserUtils.BLOCK_TITLE_BREAKOUT_SESSIONS, ParserUtils.BLOCK_TYPE_SESSION, startTime, endTime, batch, resolver); builder.withValue(Sessions.BLOCK_ID, blockId); // Assign room final String roomId = sanitizeId(entry.get(Columns.SESSION_ROOM)); builder.withValue(Sessions.ROOM_ID, roomId); // Normal session details ready, write to provider batch.add(builder.build()); // Assign tracks final String[] tracks = splitComma(entry.get(Columns.SESSION_TRACK)); for (String track : tracks) { final String trackId = translateTrackIdAlias(sanitizeId(track)); batch.add(ContentProviderOperation.newInsert(sessionTracksUri) .withValue(SessionsTracks.SESSION_ID, sessionId) .withValue(SessionsTracks.TRACK_ID, trackId).build()); } // Assign speakers final String[] speakers = splitComma(entry.get(Columns.SESSION_SPEAKERS)); for (String speaker : speakers) { final String speakerId = sanitizeId(speaker, true); batch.add(ContentProviderOperation.newInsert(sessionSpeakersUri) .withValue(SessionsSpeakers.SESSION_ID, sessionId) .withValue(SessionsSpeakers.SPEAKER_ID, speakerId).build()); } } } return batch; } /** * Parse the given date and time coming from spreadsheet. This is tightly * tied to a specific format. Ideally, if the source used use RFC 3339 we * could parse quickly using {@link Time#parse3339}. * <p> * Internally assumes PST time zone and year 2011. * * @param date String of format "Wednesday May 19", usually read from * {@link Columns#SESSION_DATE}. * @param time String of format "10:45am", usually after splitting * {@link Columns#SESSION_TIME}. */ private static long parseTime(String date, String time) throws HandlerException { final String composed = String.format("%s 2011 %s -0700", date, time); try { return sTimeFormat.parse(composed).getTime(); } catch (java.text.ParseException e) { throw new HandlerException("Problem parsing timestamp", e); } } private static ContentValues querySessionDetails(Uri uri, ContentResolver resolver) { final ContentValues values = new ContentValues(); final Cursor cursor = resolver.query(uri, SessionsQuery.PROJECTION, null, null, null); try { if (cursor.moveToFirst()) { values.put(SyncColumns.UPDATED, cursor.getLong(SessionsQuery.UPDATED)); values.put(Sessions.SESSION_STARRED, cursor.getInt(SessionsQuery.STARRED)); } else { values.put(SyncColumns.UPDATED, ScheduleContract.UPDATED_NEVER); } } finally { cursor.close(); } return values; } private interface SessionsQuery { String[] PROJECTION = { SyncColumns.UPDATED, Sessions.SESSION_STARRED, }; int UPDATED = 0; int STARRED = 1; } /** Columns coming from remote spreadsheet. */ private interface Columns { String SESSION_DATE = "sessiondate"; String SESSION_TIME = "sessiontime"; String SESSION_ROOM = "sessionroom"; String SESSION_TRACK = "sessiontrack"; String SESSION_LEVEL = "sessionlevel"; String SESSION_TITLE = "sessiontitle"; String SESSION_TAGS = "sessiontags"; String SESSION_HASHTAG = "sessionhashtag"; String SESSION_SLUG = "sessionslug"; String SESSION_SPEAKERS = "sessionspeakers"; String SESSION_ABSTRACT = "sessionabstract"; String SESSION_REQUIREMENTS = "sessionrequirements"; String SESSION_URL = "sessionurl"; String SESSION_MODERATOR_URL = "sessionmoderatorurl"; String SESSION_YOUTUBE_URL = "sessionyoutubeurl"; String SESSION_PDF_URL = "sessionpdfurl"; String SESSION_FEEDBACK_URL = "sessionfeedbackurl"; String SESSION_NOTES_URL = "sessionnotesurl"; // session_date: Wednesday May 19 // session_time: 10:45am-11:45am // session_room: 6 // session_track: Enterprise, App Engine // session_level: 201 // session_title: Run corporate applications on Google App Engine? Yes we do. // session_slug: run-corporate-applications // session_tags: Enterprise, SaaS, PaaS, Hosting, App Engine, Java // session_speakers: Ben Fried, John Smith // session_abstract: And you can too! Come hear Google's CIO Ben Fried describe... // session_requirements: None // session_url: http://www.google.com/events/io/2011/foo // session_hashtag: #io11android1 // session_youtube_url // session_pdf_url // session_feedback_url // session_moderator_url // session_notes_url } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.Speakers; import com.google.android.apps.iosched.provider.ScheduleContract.Vendors; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.Maps; import com.google.android.apps.iosched.util.ParserUtils; import com.google.android.apps.iosched.util.WorksheetEntry; import org.apache.http.client.methods.HttpGet; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.net.Uri; import android.util.Log; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.ENTRY; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.START_TAG; public class RemoteWorksheetsHandler extends XmlHandler { private static final String TAG = "WorksheetsHandler"; private RemoteExecutor mExecutor; public RemoteWorksheetsHandler(RemoteExecutor executor) { super(ScheduleContract.CONTENT_AUTHORITY); mExecutor = executor; } @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final HashMap<String, WorksheetEntry> sheets = Maps.newHashMap(); // walk response, collecting all known spreadsheets int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG && ENTRY.equals(parser.getName())) { final WorksheetEntry entry = WorksheetEntry.fromParser(parser); Log.d(TAG, "found worksheet " + entry.toString()); sheets.put(entry.getTitle(), entry); } } // consider updating each spreadsheet based on update timestamp considerUpdate(sheets, Worksheets.SESSIONS, Sessions.CONTENT_URI, resolver); considerUpdate(sheets, Worksheets.SPEAKERS, Speakers.CONTENT_URI, resolver); considerUpdate(sheets, Worksheets.VENDORS, Vendors.CONTENT_URI, resolver); return Lists.newArrayList(); } private void considerUpdate(HashMap<String, WorksheetEntry> sheets, String sheetName, Uri targetDir, ContentResolver resolver) throws HandlerException { final WorksheetEntry entry = sheets.get(sheetName); if (entry == null) { // Silently ignore missing spreadsheets to allow sync to continue. Log.w(TAG, "Missing '" + sheetName + "' worksheet data"); return; // throw new HandlerException("Missing '" + sheetName + "' worksheet data"); } final long localUpdated = ParserUtils.queryDirUpdated(targetDir, resolver); final long serverUpdated = entry.getUpdated(); Log.d(TAG, "considerUpdate() for " + entry.getTitle() + " found localUpdated=" + localUpdated + ", server=" + serverUpdated); if (localUpdated >= serverUpdated) return; final HttpGet request = new HttpGet(entry.getListFeed()); final XmlHandler handler = createRemoteHandler(entry); mExecutor.execute(request, handler); } private XmlHandler createRemoteHandler(WorksheetEntry entry) { final String title = entry.getTitle(); if (Worksheets.SESSIONS.equals(title)) { return new RemoteSessionsHandler(); } else if (Worksheets.SPEAKERS.equals(title)) { return new RemoteSpeakersHandler(); } else if (Worksheets.VENDORS.equals(title)) { return new RemoteVendorsHandler(); } else { throw new IllegalArgumentException("Unknown worksheet type"); } } interface Worksheets { String SESSIONS = "sessions"; String SPEAKERS = "speakers"; String VENDORS = "sandbox"; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.io.XmlHandler.HandlerException; import com.google.android.apps.iosched.util.ParserUtils; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentResolver; import android.content.Context; import android.content.res.Resources; import android.content.res.XmlResourceParser; import java.io.IOException; import java.io.InputStream; /** * Opens a local {@link Resources#getXml(int)} and passes the resulting * {@link XmlPullParser} to the given {@link XmlHandler}. */ public class LocalExecutor { private Resources mRes; private ContentResolver mResolver; public LocalExecutor(Resources res, ContentResolver resolver) { mRes = res; mResolver = resolver; } public void execute(Context context, String assetName, XmlHandler handler) throws HandlerException { try { final InputStream input = context.getAssets().open(assetName); final XmlPullParser parser = ParserUtils.newPullParser(input); handler.parseAndApply(parser, mResolver); } catch (HandlerException e) { throw e; } catch (XmlPullParserException e) { throw new HandlerException("Problem parsing local asset: " + assetName, e); } catch (IOException e) { throw new HandlerException("Problem parsing local asset: " + assetName, e); } } public void execute(int resId, XmlHandler handler) throws HandlerException { final XmlResourceParser parser = mRes.getXml(resId); try { handler.parseAndApply(parser, mResolver); } finally { parser.close(); } } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.io.XmlHandler.HandlerException; import com.google.android.apps.iosched.util.ParserUtils; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpUriRequest; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentResolver; import java.io.IOException; import java.io.InputStream; /** * Executes an {@link HttpUriRequest} and passes the result as an * {@link XmlPullParser} to the given {@link XmlHandler}. */ public class RemoteExecutor { private final HttpClient mHttpClient; private final ContentResolver mResolver; public RemoteExecutor(HttpClient httpClient, ContentResolver resolver) { mHttpClient = httpClient; mResolver = resolver; } /** * Execute a {@link HttpGet} request, passing a valid response through * {@link XmlHandler#parseAndApply(XmlPullParser, ContentResolver)}. */ public void executeGet(String url, XmlHandler handler) throws HandlerException { final HttpUriRequest request = new HttpGet(url); execute(request, handler); } /** * Execute this {@link HttpUriRequest}, passing a valid response through * {@link XmlHandler#parseAndApply(XmlPullParser, ContentResolver)}. */ public void execute(HttpUriRequest request, XmlHandler handler) throws HandlerException { try { final HttpResponse resp = mHttpClient.execute(request); final int status = resp.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { throw new HandlerException("Unexpected server response " + resp.getStatusLine() + " for " + request.getRequestLine()); } final InputStream input = resp.getEntity().getContent(); try { final XmlPullParser parser = ParserUtils.newPullParser(input); handler.parseAndApply(parser, mResolver); } catch (XmlPullParserException e) { throw new HandlerException("Malformed response for " + request.getRequestLine(), e); } finally { if (input != null) input.close(); } } catch (HandlerException e) { throw e; } catch (IOException e) { throw new HandlerException("Problem reading remote response for " + request.getRequestLine(), e); } } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.ParserUtils; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProviderOperation; import android.content.ContentResolver; import java.io.IOException; import java.util.ArrayList; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.END_TAG; import static org.xmlpull.v1.XmlPullParser.START_TAG; import static org.xmlpull.v1.XmlPullParser.TEXT; public class LocalBlocksHandler extends XmlHandler { public LocalBlocksHandler() { super(ScheduleContract.CONTENT_AUTHORITY); } @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); // Clear any existing static blocks, as they may have been updated. final String selection = Blocks.BLOCK_TYPE + "=? OR " + Blocks.BLOCK_TYPE +"=?"; final String[] selectionArgs = { ParserUtils.BLOCK_TYPE_FOOD, ParserUtils.BLOCK_TYPE_OFFICE_HOURS }; batch.add(ContentProviderOperation.newDelete(Blocks.CONTENT_URI) .withSelection(selection, selectionArgs).build()); int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG && Tags.BLOCK.equals(parser.getName())) { batch.add(parseBlock(parser)); } } return batch; } private static ContentProviderOperation parseBlock(XmlPullParser parser) throws XmlPullParserException, IOException { final int depth = parser.getDepth(); final ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Blocks.CONTENT_URI); String title = null; long startTime = -1; long endTime = -1; String blockType = null; String tag = null; int type; while (((type = parser.next()) != END_TAG || parser.getDepth() > depth) && type != END_DOCUMENT) { if (type == START_TAG) { tag = parser.getName(); } else if (type == END_TAG) { tag = null; } else if (type == TEXT) { final String text = parser.getText(); if (Tags.TITLE.equals(tag)) { title = text; } else if (Tags.START.equals(tag)) { startTime = ParserUtils.parseTime(text); } else if (Tags.END.equals(tag)) { endTime = ParserUtils.parseTime(text); } else if (Tags.TYPE.equals(tag)) { blockType = text; } } } final String blockId = Blocks.generateBlockId(startTime, endTime); builder.withValue(Blocks.BLOCK_ID, blockId); builder.withValue(Blocks.BLOCK_TITLE, title); builder.withValue(Blocks.BLOCK_START, startTime); builder.withValue(Blocks.BLOCK_END, endTime); builder.withValue(Blocks.BLOCK_TYPE, blockType); return builder.build(); } interface Tags { String BLOCK = "block"; String TITLE = "title"; String START = "start"; String END = "end"; String TYPE = "type"; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.Context; import android.test.AndroidTestCase; import java.io.IOException; import java.lang.reflect.InvocationTargetException; public class SpreadsheetEntryTest extends AndroidTestCase { public void testParseNormal() throws Exception { final XmlPullParser parser = openAssetParser("spreadsheet-normal.xml"); final SpreadsheetEntry entry = SpreadsheetEntry.fromParser(parser); assertEquals("unexpected columns", 19, entry.size()); assertEquals("Wednesday May 19", entry.get("sessiondate")); assertEquals("10:45am-11:45am", entry.get("sessiontime")); assertEquals("6", entry.get("room")); assertEquals("Android", entry.get("product")); assertEquals("Android", entry.get("track")); assertEquals("101", entry.get("sessiontype")); assertEquals("A beginner's guide to Android", entry.get("sessiontitle")); assertEquals("Android, Mobile, Java", entry.get("tags")); assertEquals("Reto Meier", entry.get("sessionspeakers")); assertEquals("retomeier", entry.get("speakers")); assertEquals("This session will introduce some of the basic concepts involved in " + "Android development. Starting with an overview of the SDK APIs available " + "to developers, we will work through some simple code examples that " + "explore some of the more common user features including using sensors, " + "maps, and geolocation.", entry.get("sessionabstract")); assertEquals("Proficiency in Java and a basic understanding of embedded " + "environments like mobile phones", entry.get("sessionrequirements")); assertEquals("beginners-guide-android", entry.get("sessionlink")); assertEquals("#android1", entry.get("sessionhashtag")); assertEquals("http://www.google.com/moderator/#15/e=68f0&t=68f0.45", entry.get("moderatorlink")); assertEquals( "https://wave.google.com/wave/#restored:wave:googlewave.com!w%252B-Xhdu7ZkBHw", entry.get("wavelink")); assertEquals("https://wave.google.com/wave/#restored:wave:googlewave.com", entry.get("_e8rn7")); assertEquals("w%252B-Xhdu7ZkBHw", entry.get("_dmair")); assertEquals("w+-Xhdu7ZkBHw", entry.get("waveid")); } public void testParseEmpty() throws Exception { final XmlPullParser parser = openAssetParser("spreadsheet-empty.xml"); final SpreadsheetEntry entry = SpreadsheetEntry.fromParser(parser); assertEquals("unexpected columns", 0, entry.size()); } public void testParseEmptyField() throws Exception { final XmlPullParser parser = openAssetParser("spreadsheet-emptyfield.xml"); final SpreadsheetEntry entry = SpreadsheetEntry.fromParser(parser); assertEquals("unexpected columns", 3, entry.size()); assertEquals("Wednesday May 19", entry.get("sessiondate")); assertEquals("", entry.get("sessiontime")); assertEquals("6", entry.get("room")); } public void testParseSingle() throws Exception { final XmlPullParser parser = openAssetParser("spreadsheet-single.xml"); final SpreadsheetEntry entry = SpreadsheetEntry.fromParser(parser); assertEquals("unexpected columns", 1, entry.size()); assertEquals("Wednesday May 19", entry.get("sessiondate")); } private XmlPullParser openAssetParser(String assetName) throws XmlPullParserException, IOException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { final Context testContext = getTestContext(this); return ParserUtils.newPullParser(testContext.getResources().getAssets().open(assetName)); } /** * Exposes method {@code getTestContext()} in {@link AndroidTestCase}, which * is hidden for now. Useful for obtaining access to the test assets. */ public static Context getTestContext(AndroidTestCase testCase) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return (Context) AndroidTestCase.class.getMethod("getTestContext").invoke(testCase); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.StatusLine; import org.apache.http.client.AuthenticationHandler; import org.apache.http.client.HttpClient; import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.RedirectHandler; import org.apache.http.client.RequestDirector; import org.apache.http.client.UserTokenHandler; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.ConnectionKeepAliveStrategy; import org.apache.http.conn.routing.HttpRoutePlanner; import org.apache.http.entity.InputStreamEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicHttpResponse; import org.apache.http.message.BasicStatusLine; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.HttpRequestExecutor; import android.content.Context; import android.content.res.AssetManager; import android.test.AndroidTestCase; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; /** * Stub {@link HttpClient} that will provide a single {@link HttpResponse} to * any incoming {@link HttpRequest}. This single response can be set using * {@link #setResponse(HttpResponse)}. */ class StubHttpClient extends DefaultHttpClient { private static final String TAG = "StubHttpClient"; private HttpResponse mResponse; private HttpRequest mLastRequest; public StubHttpClient() { resetState(); } /** * Set the default {@link HttpResponse} to always return for any * {@link #execute(HttpUriRequest)} calls. */ public void setResponse(HttpResponse currentResponse) { mResponse = currentResponse; } /** * Set the default {@link HttpResponse} to always return for any * {@link #execute(HttpUriRequest)} calls. This is a shortcut instead of * calling {@link #buildResponse(int, String, AndroidTestCase)}. */ public void setResponse(int statusCode, String assetName, AndroidTestCase testCase) throws Exception { setResponse(buildResponse(statusCode, assetName, testCase)); } /** * Return the last {@link HttpRequest} that was requested through * {@link #execute(HttpUriRequest)}, exposed for testing purposes. */ public HttpRequest getLastRequest() { return mLastRequest; } /** * Reset any internal state, usually so this heavy {@link HttpClient} can be * reused across tests. */ public void resetState() { mResponse = buildInternalServerError(); } private static HttpResponse buildInternalServerError() { final StatusLine status = new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_INTERNAL_SERVER_ERROR, null); return new BasicHttpResponse(status); } /** * Build a stub {@link HttpResponse}, probably for use with * {@link #setResponse(HttpResponse)}. * * @param statusCode {@link HttpStatus} code to use. * @param assetName Name of asset that should be included as a single * {@link HttpEntity} to be included in the response, loaded * through {@link AssetManager}. */ public static HttpResponse buildResponse(int statusCode, String assetName, AndroidTestCase testCase) throws Exception { final Context testContext = getTestContext(testCase); return buildResponse(statusCode, assetName, testContext); } /** * Exposes method {@code getTestContext()} in {@link AndroidTestCase}, which * is hidden for now. Useful for obtaining access to the test assets. */ public static Context getTestContext(AndroidTestCase testCase) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return (Context) AndroidTestCase.class.getMethod("getTestContext").invoke(testCase); } /** * Build a stub {@link HttpResponse}, probably for use with * {@link #setResponse(HttpResponse)}. * * @param statusCode {@link HttpStatus} code to use. * @param assetName Name of asset that should be included as a single * {@link HttpEntity} to be included in the response, loaded * through {@link AssetManager}. */ public static HttpResponse buildResponse(int statusCode, String assetName, Context context) throws IOException { final StatusLine status = new BasicStatusLine(HttpVersion.HTTP_1_1, statusCode, null); final HttpResponse response = new BasicHttpResponse(status); if (assetName != null) { final InputStream entity = context.getAssets().open(assetName); response.setEntity(new InputStreamEntity(entity, entity.available())); } return response; } /** {@inheritDoc} */ @Override protected RequestDirector createClientRequestDirector( final HttpRequestExecutor requestExec, final ClientConnectionManager conman, final ConnectionReuseStrategy reustrat, final ConnectionKeepAliveStrategy kastrat, final HttpRoutePlanner rouplan, final HttpProcessor httpProcessor, final HttpRequestRetryHandler retryHandler, final RedirectHandler redirectHandler, final AuthenticationHandler targetAuthHandler, final AuthenticationHandler proxyAuthHandler, final UserTokenHandler stateHandler, final HttpParams params) { return new RequestDirector() { /** {@inheritDoc} */ public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException, IOException { Log.d(TAG, "Intercepted: " + request.getRequestLine().toString()); mLastRequest = request; return mResponse; } }; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleProvider; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.Tracks; import com.google.android.apps.iosched.util.ParserUtils; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.test.AndroidTestCase; import android.test.ProviderTestCase2; import java.io.IOException; import java.lang.reflect.InvocationTargetException; public class SessionsHandlerTest extends ProviderTestCase2<ScheduleProvider> { public SessionsHandlerTest() { super(ScheduleProvider.class, ScheduleContract.CONTENT_AUTHORITY); } public void testLocalHandler() throws Exception { parseBlocks(); parseTracks(); parseRooms(); final ContentResolver resolver = getMockContentResolver(); final XmlPullParser parser = openAssetParser("local-sessions.xml"); new LocalSessionsHandler().parseAndApply(parser, resolver); Cursor cursor = resolver.query(Sessions.CONTENT_URI, null, null, null, Sessions.DEFAULT_SORT); try { assertEquals(2, cursor.getCount()); assertTrue(cursor.moveToNext()); assertEquals("writingreal-timegamesforandroidredux", getString(cursor, Sessions.SESSION_ID)); assertEquals("Writing real-time games for Android redux", getString(cursor, Sessions.TITLE)); assertEquals(6, getInt(cursor, Sessions.ROOM_ID)); assertEquals(2, getInt(cursor, Sessions.ROOM_FLOOR)); assertEquals(ParserUtils.BLOCK_TYPE_OFFICE_HOURS, getString(cursor, Sessions.BLOCK_TYPE)); assertEquals(1274270400000L, getLong(cursor, Sessions.BLOCK_START)); assertEquals(1274295600000L, getLong(cursor, Sessions.BLOCK_END)); assertTrue(cursor.moveToNext()); assertEquals("beginners-guide-android", getString(cursor, Sessions.SESSION_ID)); assertEquals("A beginner's guide to Android", getString(cursor, Sessions.TITLE)); assertEquals(4, getInt(cursor, Sessions.ROOM_ID)); assertEquals(2, getInt(cursor, Sessions.ROOM_FLOOR)); assertEquals(ParserUtils.BLOCK_TYPE_OFFICE_HOURS, getString(cursor, Sessions.BLOCK_TYPE)); assertEquals(1274291100000L, getLong(cursor, Sessions.BLOCK_START)); assertEquals(1274294700000L, getLong(cursor, Sessions.BLOCK_END)); } finally { cursor.close(); } final Uri sessionTracks = Sessions.buildTracksDirUri("beginners-guide-android"); cursor = resolver.query(sessionTracks, null, null, null, Tracks.DEFAULT_SORT); try { assertEquals(1, cursor.getCount()); assertTrue(cursor.moveToNext()); assertEquals("beginners-guide-android", getString(cursor, Sessions.SESSION_ID)); assertEquals("android", getString(cursor, Tracks.TRACK_ID)); assertEquals(-14002535, getInt(cursor, Tracks.TRACK_COLOR)); } finally { cursor.close(); } } public void testRemoteHandler() throws Exception { parseTracks(); parseRooms(); final ContentResolver resolver = getMockContentResolver(); final XmlPullParser parser = openAssetParser("remote-sessions1.xml"); new RemoteSessionsHandler().parseAndApply(parser, resolver); Cursor cursor = resolver.query(Sessions.CONTENT_URI, null, null, null, Sessions.DEFAULT_SORT); try { assertEquals(6, cursor.getCount()); assertTrue(cursor.moveToNext()); assertEquals("beginners-guide-android", getString(cursor, Sessions.SESSION_ID)); assertEquals(6, getInt(cursor, Sessions.ROOM_ID)); assertEquals(2, getInt(cursor, Sessions.ROOM_FLOOR)); assertEquals(ParserUtils.BLOCK_TYPE_SESSION, getString(cursor, Sessions.BLOCK_TYPE)); assertEquals(1274291100000L, getLong(cursor, Sessions.BLOCK_START)); assertEquals(1274294700000L, getLong(cursor, Sessions.BLOCK_END)); assertEquals("http://www.google.com/moderator/#15/e=68f0&t=68f0.45", getString(cursor, Sessions.MODERATOR_URL)); assertTrue(cursor.moveToNext()); assertEquals("writing-real-time-games-android", getString(cursor, Sessions.SESSION_ID)); assertEquals(ParserUtils.BLOCK_TYPE_SESSION, getString(cursor, Sessions.BLOCK_TYPE)); assertTrue(cursor.moveToLast()); assertEquals("developing-restful-android-apps", getString(cursor, Sessions.SESSION_ID)); assertEquals(ParserUtils.BLOCK_TYPE_SESSION, getString(cursor, Sessions.BLOCK_TYPE)); } finally { cursor.close(); } final Uri sessionTracks = Sessions.buildTracksDirUri("android-ui-design-patterns"); cursor = resolver.query(sessionTracks, null, null, null, Tracks.DEFAULT_SORT); try { assertEquals(2, cursor.getCount()); assertTrue(cursor.moveToNext()); assertEquals("android-ui-design-patterns", getString(cursor, Sessions.SESSION_ID)); assertEquals("android", getString(cursor, Tracks.TRACK_ID)); assertEquals(-14002535, getInt(cursor, Tracks.TRACK_COLOR)); assertTrue(cursor.moveToNext()); assertEquals("android-ui-design-patterns", getString(cursor, Sessions.SESSION_ID)); assertEquals("enterprise", getString(cursor, Tracks.TRACK_ID)); assertEquals(-15750145, getInt(cursor, Tracks.TRACK_COLOR)); } finally { cursor.close(); } } public void testLocalRemoteUpdate() throws Exception { parseBlocks(); parseTracks(); parseRooms(); // first, insert session data from local source final ContentResolver resolver = getMockContentResolver(); final XmlPullParser parser = openAssetParser("local-sessions.xml"); new LocalSessionsHandler().parseAndApply(parser, resolver); // now, star one of the sessions final Uri sessionUri = Sessions.buildSessionUri("beginners-guide-android"); final ContentValues values = new ContentValues(); values.put(Sessions.STARRED, 1); resolver.update(sessionUri, values, null, null); Cursor cursor = resolver.query(Sessions.CONTENT_URI, null, null, null, Sessions.DEFAULT_SORT); try { assertEquals(2, cursor.getCount()); assertTrue(cursor.moveToNext()); assertEquals("writingreal-timegamesforandroidredux", getString(cursor, Sessions.SESSION_ID)); assertEquals(ParserUtils.BLOCK_TYPE_OFFICE_HOURS, getString(cursor, Sessions.BLOCK_TYPE)); assertEquals(0, getInt(cursor, Sessions.STARRED)); assertEquals(0L, getLong(cursor, Sessions.UPDATED)); // make sure session is starred assertTrue(cursor.moveToNext()); assertEquals("beginners-guide-android", getString(cursor, Sessions.SESSION_ID)); assertEquals(4, getInt(cursor, Sessions.ROOM_ID)); assertEquals(2, getInt(cursor, Sessions.ROOM_FLOOR)); assertEquals(ParserUtils.BLOCK_TYPE_OFFICE_HOURS, getString(cursor, Sessions.BLOCK_TYPE)); assertEquals(1274291100000L, getLong(cursor, Sessions.BLOCK_START)); assertEquals(1274294700000L, getLong(cursor, Sessions.BLOCK_END)); assertEquals(1, getInt(cursor, Sessions.STARRED)); assertEquals(0L, getLong(cursor, Sessions.UPDATED)); } finally { cursor.close(); } // second, perform remote sync to pull in updates final XmlPullParser parser1 = openAssetParser("remote-sessions1.xml"); new RemoteSessionsHandler().parseAndApply(parser1, resolver); cursor = resolver.query(Sessions.CONTENT_URI, null, null, null, Sessions.DEFAULT_SORT); try { // six sessions from remote sync, plus one original assertEquals(7, cursor.getCount()); // original local-only session is still hanging around assertTrue(cursor.moveToNext()); assertEquals("writingreal-timegamesforandroidredux", getString(cursor, Sessions.SESSION_ID)); assertEquals(ParserUtils.BLOCK_TYPE_OFFICE_HOURS, getString(cursor, Sessions.BLOCK_TYPE)); assertEquals(0, getInt(cursor, Sessions.STARRED)); assertEquals(0L, getLong(cursor, Sessions.UPDATED)); // existing session was updated with remote values, and has star assertTrue(cursor.moveToNext()); assertEquals("beginners-guide-android", getString(cursor, Sessions.SESSION_ID)); assertEquals(1, getInt(cursor, Sessions.STARRED)); assertEquals(ParserUtils.BLOCK_TYPE_SESSION, getString(cursor, Sessions.BLOCK_TYPE)); assertEquals(1273186984000L, getLong(cursor, Sessions.UPDATED)); // make sure session block was updated from remote assertTrue(cursor.moveToNext()); assertEquals("writing-real-time-games-android", getString(cursor, Sessions.SESSION_ID)); assertEquals(6, getInt(cursor, Sessions.ROOM_ID)); assertEquals(2, getInt(cursor, Sessions.ROOM_FLOOR)); assertEquals(ParserUtils.BLOCK_TYPE_SESSION, getString(cursor, Sessions.BLOCK_TYPE)); assertEquals(1274297400000L, getLong(cursor, Sessions.BLOCK_START)); assertEquals(1274301000000L, getLong(cursor, Sessions.BLOCK_END)); assertEquals("This session is a crash course in Android game development: everything " + "you need to know to get started writing 2D and 3D games, as well as tips, " + "tricks, and benchmarks to help your code reach optimal performance. In " + "addition, we'll discuss hot topics related to game development, including " + "hardware differences across devices, using C++ to write Android games, " + "and the traits of the most popular games on Market.", getString(cursor, Sessions.ABSTRACT)); assertEquals("Proficiency in Java and a solid grasp of Android's fundamental concepts", getString(cursor, Sessions.REQUIREMENTS)); assertEquals("http://www.google.com/moderator/#15/e=68f0&t=68f0.9B", getString(cursor, Sessions.MODERATOR_URL)); assertEquals(0, getInt(cursor, Sessions.STARRED)); assertEquals(1273186984000L, getLong(cursor, Sessions.UPDATED)); assertTrue(cursor.moveToLast()); assertEquals("developing-restful-android-apps", getString(cursor, Sessions.SESSION_ID)); assertEquals("301", getString(cursor, Sessions.TYPE)); assertEquals(0, getInt(cursor, Sessions.STARRED)); assertEquals(ParserUtils.BLOCK_TYPE_SESSION, getString(cursor, Sessions.BLOCK_TYPE)); assertEquals(1273186984000L, getLong(cursor, Sessions.UPDATED)); } finally { cursor.close(); } // third, perform another remote sync final XmlPullParser parser2 = openAssetParser("remote-sessions2.xml"); new RemoteSessionsHandler().parseAndApply(parser2, resolver); cursor = resolver.query(Sessions.CONTENT_URI, null, null, null, Sessions.DEFAULT_SORT); try { // six sessions from remote sync, plus one original assertEquals(7, cursor.getCount()); // original local-only session is still hanging around assertTrue(cursor.moveToNext()); assertEquals("writingreal-timegamesforandroidredux", getString(cursor, Sessions.SESSION_ID)); assertEquals(ParserUtils.BLOCK_TYPE_OFFICE_HOURS, getString(cursor, Sessions.BLOCK_TYPE)); assertEquals(0, getInt(cursor, Sessions.STARRED)); assertEquals(0L, getLong(cursor, Sessions.UPDATED)); // existing session was updated with remote values, and has star assertTrue(cursor.moveToNext()); assertEquals("beginners-guide-android", getString(cursor, Sessions.SESSION_ID)); assertEquals(ParserUtils.BLOCK_TYPE_SESSION, getString(cursor, Sessions.BLOCK_TYPE)); assertEquals(1, getInt(cursor, Sessions.STARRED)); assertEquals(1273186984000L, getLong(cursor, Sessions.UPDATED)); // existing session was updated with remote values, and has star assertTrue(cursor.moveToNext()); assertEquals("writing-real-time-games-android", getString(cursor, Sessions.SESSION_ID)); assertEquals("Proficiency in Java and Python and Ruby and Scheme and " + "Bash and Ada and a solid grasp of Android's fundamental concepts", getString(cursor, Sessions.REQUIREMENTS)); assertEquals(0, getInt(cursor, Sessions.STARRED)); assertEquals(ParserUtils.BLOCK_TYPE_SESSION, getString(cursor, Sessions.BLOCK_TYPE)); assertEquals(1273532584000L, getLong(cursor, Sessions.UPDATED)); // last session should remain unchanged, since updated flag didn't // get touched. the remote spreadsheet said "102401", but we should // still have "301". assertTrue(cursor.moveToLast()); assertEquals("developing-restful-android-apps", getString(cursor, Sessions.SESSION_ID)); assertEquals("301", getString(cursor, Sessions.TYPE)); assertEquals(ParserUtils.BLOCK_TYPE_SESSION, getString(cursor, Sessions.BLOCK_TYPE)); assertEquals(1273186984000L, getLong(cursor, Sessions.UPDATED)); } finally { cursor.close(); } } private void parseBlocks() throws Exception { final XmlPullParser parser = openAssetParser("local-blocks.xml"); new LocalBlocksHandler().parseAndApply(parser, getMockContentResolver()); } private void parseTracks() throws Exception { final XmlPullParser parser = openAssetParser("local-tracks.xml"); new LocalTracksHandler().parseAndApply(parser, getMockContentResolver()); } private void parseRooms() throws Exception { final XmlPullParser parser = openAssetParser("local-rooms.xml"); new LocalRoomsHandler().parseAndApply(parser, getMockContentResolver()); } private String getString(Cursor cursor, String column) { return cursor.getString(cursor.getColumnIndex(column)); } private long getInt(Cursor cursor, String column) { return cursor.getInt(cursor.getColumnIndex(column)); } private long getLong(Cursor cursor, String column) { return cursor.getLong(cursor.getColumnIndex(column)); } private XmlPullParser openAssetParser(String assetName) throws XmlPullParserException, IOException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { final Context testContext = getTestContext(this); return ParserUtils.newPullParser(testContext.getResources().getAssets().open(assetName)); } /** * Exposes method {@code getTestContext()} in {@link AndroidTestCase}, which * is hidden for now. Useful for obtaining access to the test assets. */ public static Context getTestContext(AndroidTestCase testCase) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return (Context) AndroidTestCase.class.getMethod("getTestContext").invoke(testCase); } }
Java
/*** Copyright (c) 2008-2009 CommonsWare, LLC Portions (c) 2009 Google, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.commonsware.cwac.sacklist; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListAdapter; import java.util.ArrayList; import java.util.List; /** * Adapter that simply returns row views from a list. * * If you supply a size, you must implement newView(), to * create a required view. The adapter will then cache these * views. * * If you supply a list of views in the constructor, that * list will be used directly. If any elements in the list * are null, then newView() will be called just for those * slots. * * Subclasses may also wish to override areAllItemsEnabled() * (default: false) and isEnabled() (default: false), if some * of their rows should be selectable. * * It is assumed each view is unique, and therefore will not * get recycled. * * Note that this adapter is not designed for long lists. It * is more for screens that should behave like a list. This * is particularly useful if you combine this with other * adapters (e.g., SectionedAdapter) that might have an * arbitrary number of rows, so it all appears seamless. */ public class SackOfViewsAdapter extends BaseAdapter { private List<View> views=null; /** * Constructor creating an empty list of views, but with * a specified count. Subclasses must override newView(). */ public SackOfViewsAdapter(int count) { super(); views=new ArrayList<View>(count); for (int i=0;i<count;i++) { views.add(null); } } /** * Constructor wrapping a supplied list of views. * Subclasses must override newView() if any of the elements * in the list are null. */ public SackOfViewsAdapter(List<View> views) { super(); this.views=views; } /** * Get the data item associated with the specified * position in the data set. * @param position Position of the item whose data we want */ @Override public Object getItem(int position) { return(views.get(position)); } /** * How many items are in the data set represented by this * Adapter. */ @Override public int getCount() { return(views.size()); } /** * Returns the number of types of Views that will be * created by getView(). */ @Override public int getViewTypeCount() { return(getCount()); } /** * Get the type of View that will be created by getView() * for the specified item. * @param position Position of the item whose data we want */ @Override public int getItemViewType(int position) { return(position); } /** * Are all items in this ListAdapter enabled? If yes it * means all items are selectable and clickable. */ @Override public boolean areAllItemsEnabled() { return(false); } /** * Returns true if the item at the specified position is * not a separator. * @param position Position of the item whose data we want */ @Override public boolean isEnabled(int position) { return(false); } /** * Get a View that displays the data at the specified * position in the data set. * @param position Position of the item whose data we want * @param convertView View to recycle, if not null * @param parent ViewGroup containing the returned View */ @Override public View getView(int position, View convertView, ViewGroup parent) { View result=views.get(position); if (result==null) { result=newView(position, parent); views.set(position, result); } return(result); } /** * Get the row id associated with the specified position * in the list. * @param position Position of the item whose data we want */ @Override public long getItemId(int position) { return(position); } /** * Create a new View to go into the list at the specified * position. * @param position Position of the item whose data we want * @param parent ViewGroup containing the returned View */ protected View newView(int position, ViewGroup parent) { throw new RuntimeException("You must override newView()!"); } }
Java
/*** Copyright (c) 2008-2009 CommonsWare, LLC Portions (c) 2009 Google, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.commonsware.cwac.merge; import android.database.DataSetObserver; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListAdapter; import android.widget.SectionIndexer; import java.util.ArrayList; import java.util.List; import com.commonsware.cwac.sacklist.SackOfViewsAdapter; /** * Adapter that merges multiple child adapters and views * into a single contiguous whole. * * Adapters used as pieces within MergeAdapter must * have view type IDs monotonically increasing from 0. Ideally, * adapters also have distinct ranges for their row ids, as * returned by getItemId(). * */ public class MergeAdapter extends BaseAdapter implements SectionIndexer { private ArrayList<ListAdapter> pieces=new ArrayList<ListAdapter>(); /** * Stock constructor, simply chaining to the superclass. */ public MergeAdapter() { super(); } /** * Adds a new adapter to the roster of things to appear * in the aggregate list. * @param adapter Source for row views for this section */ public void addAdapter(ListAdapter adapter) { pieces.add(adapter); adapter.registerDataSetObserver(new CascadeDataSetObserver()); } /** * Adds a new View to the roster of things to appear * in the aggregate list. * @param view Single view to add */ public void addView(View view) { addView(view, false); } /** * Adds a new View to the roster of things to appear * in the aggregate list. * @param view Single view to add * @param enabled false if views are disabled, true if enabled */ public void addView(View view, boolean enabled) { ArrayList<View> list=new ArrayList<View>(1); list.add(view); addViews(list, enabled); } /** * Adds a list of views to the roster of things to appear * in the aggregate list. * @param views List of views to add */ public void addViews(List<View> views) { addViews(views, false); } /** * Adds a list of views to the roster of things to appear * in the aggregate list. * @param views List of views to add * @param enabled false if views are disabled, true if enabled */ public void addViews(List<View> views, boolean enabled) { if (enabled) { addAdapter(new EnabledSackAdapter(views)); } else { addAdapter(new SackOfViewsAdapter(views)); } } /** * Get the data item associated with the specified * position in the data set. * @param position Position of the item whose data we want */ @Override public Object getItem(int position) { for (ListAdapter piece : pieces) { int size=piece.getCount(); if (position<size) { return(piece.getItem(position)); } position-=size; } return(null); } /** * Get the adapter associated with the specified * position in the data set. * @param position Position of the item whose adapter we want */ public ListAdapter getAdapter(int position) { for (ListAdapter piece : pieces) { int size=piece.getCount(); if (position<size) { return(piece); } position-=size; } return(null); } /** * How many items are in the data set represented by this * Adapter. */ @Override public int getCount() { int total=0; for (ListAdapter piece : pieces) { total+=piece.getCount(); } return(total); } /** * Returns the number of types of Views that will be * created by getView(). */ @Override public int getViewTypeCount() { int total=0; for (ListAdapter piece : pieces) { total+=piece.getViewTypeCount(); } return(Math.max(total, 1)); // needed for setListAdapter() before content add' } /** * Get the type of View that will be created by getView() * for the specified item. * @param position Position of the item whose data we want */ @Override public int getItemViewType(int position) { int typeOffset=0; int result=-1; for (ListAdapter piece : pieces) { int size=piece.getCount(); if (position<size) { result=typeOffset+piece.getItemViewType(position); break; } position-=size; typeOffset+=piece.getViewTypeCount(); } return(result); } /** * Are all items in this ListAdapter enabled? If yes it * means all items are selectable and clickable. */ @Override public boolean areAllItemsEnabled() { return(false); } /** * Returns true if the item at the specified position is * not a separator. * @param position Position of the item whose data we want */ @Override public boolean isEnabled(int position) { for (ListAdapter piece : pieces) { int size=piece.getCount(); if (position<size) { return(piece.isEnabled(position)); } position-=size; } return(false); } /** * Get a View that displays the data at the specified * position in the data set. * @param position Position of the item whose data we want * @param convertView View to recycle, if not null * @param parent ViewGroup containing the returned View */ @Override public View getView(int position, View convertView, ViewGroup parent) { for (ListAdapter piece : pieces) { int size=piece.getCount(); if (position<size) { return(piece.getView(position, convertView, parent)); } position-=size; } return(null); } /** * Get the row id associated with the specified position * in the list. * @param position Position of the item whose data we want */ @Override public long getItemId(int position) { for (ListAdapter piece : pieces) { int size=piece.getCount(); if (position<size) { return(piece.getItemId(position)); } position-=size; } return(-1); } @Override public int getPositionForSection(int section) { int position=0; for (ListAdapter piece : pieces) { if (piece instanceof SectionIndexer) { Object[] sections=((SectionIndexer)piece).getSections(); int numSections=0; if (sections!=null) { numSections=sections.length; } if (section<numSections) { return(position+((SectionIndexer)piece).getPositionForSection(section)); } else if (sections!=null) { section-=numSections; } } position+=piece.getCount(); } return(0); } @Override public int getSectionForPosition(int position) { int section=0; for (ListAdapter piece : pieces) { int size=piece.getCount(); if (position<size) { if (piece instanceof SectionIndexer) { return(section+((SectionIndexer)piece).getSectionForPosition(position)); } return(0); } else { if (piece instanceof SectionIndexer) { Object[] sections=((SectionIndexer)piece).getSections(); if (sections!=null) { section+=sections.length; } } } position-=size; } return(0); } @Override public Object[] getSections() { ArrayList<Object> sections=new ArrayList<Object>(); for (ListAdapter piece : pieces) { if (piece instanceof SectionIndexer) { Object[] curSections=((SectionIndexer)piece).getSections(); if (curSections!=null) { for (Object section : curSections) { sections.add(section); } } } } if (sections.size()==0) { return(null); } return(sections.toArray(new Object[0])); } private static class EnabledSackAdapter extends SackOfViewsAdapter { public EnabledSackAdapter(List<View> views) { super(views); } @Override public boolean areAllItemsEnabled() { return(true); } @Override public boolean isEnabled(int position) { return(true); } } private class CascadeDataSetObserver extends DataSetObserver { @Override public void onChanged() { notifyDataSetChanged(); } @Override public void onInvalidated() { notifyDataSetInvalidated(); } } }
Java
package com.ch_linghu.fanfoudroid; import java.text.MessageFormat; import android.app.AlertDialog; import android.app.ProgressDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.provider.BaseColumns; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.ch_linghu.fanfoudroid.data.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.data.db.UserInfoTable; import com.ch_linghu.fanfoudroid.helper.ProfileImageCacheCallback; import com.ch_linghu.fanfoudroid.helper.Utils; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.base.WithHeaderActivity; import com.ch_linghu.fanfoudroid.weibo.User; /** * * @author Dino 2011-02-26 */ public class ProfileActivity extends WithHeaderActivity { private static final String TAG = "ProfileActivity"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.PROFILE"; private static final String STATUS_COUNT = "status_count"; private static final String EXTRA_USER = "user"; private ProgressDialog dialog; private GenericTask profileInfoTask;// 获取用户信息 private GenericTask setFollowingTask; private GenericTask cancelFollowingTask; private String userId; private String myself; private User profileInfo;// 用户信息 private ImageView profileImageView;// 头像 private TextView profileName;// 名称 private TextView profileScreenName;// 昵称 private TextView userLocation;// 地址 private TextView userUrl;// url private TextView userInfo;// 自述 private TextView friendsCount;// 好友 private TextView followersCount;// 收听 private TextView statusCount;// 消息 private TextView favouritesCount;// 收藏 private TextView isFollowingText;// 是否收听 private Button followingBtn;// 收听/取消收听按钮 private Button sendMentionBtn;// 发送留言按钮 private Button sendDmBtn;// 发送私信按钮 private RelativeLayout friendsLayout; private LinearLayout followersLayout; private LinearLayout statusesLayout; private LinearLayout favouritesLayout; private static final String FANFOUROOT = "http://fanfou.com/"; private static final String USER_ID = "userid"; private TwitterDatabase db; public static Intent createIntent(String userId) { Intent intent = new Intent(LAUNCH_ACTION); intent.putExtra(USER_ID, userId); return intent; } private ProfileImageCacheCallback callback = new ProfileImageCacheCallback() { @Override public void refresh(String url, Bitmap bitmap) { profileImageView.setImageBitmap(bitmap); } }; @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "OnCreate start"); if (super._onCreate(savedInstanceState)) { setContentView(R.layout.profile); Intent intent = getIntent(); Bundle extras = intent.getExtras(); myself = TwitterApplication.getMyselfId(); if (extras != null) { this.userId = extras.getString(USER_ID); } else { this.userId = myself; } Uri data = intent.getData(); if (data != null) { userId = data.getLastPathSegment(); } if (userId.equals(myself)) { initHeader(HEADER_STYLE_HOME); } else { initHeader(HEADER_STYLE_BACK); } // 初始化控件 initControls(); Log.i(TAG, "the userid is " + userId); db = this.getDb(); draw(); return true; } else { return false; } } private void initControls() { sendMentionBtn = (Button) findViewById(R.id.sendmetion_btn); sendDmBtn = (Button) findViewById(R.id.senddm_btn); profileImageView = (ImageView) findViewById(R.id.profileimage); profileName = (TextView) findViewById(R.id.profilename); profileScreenName = (TextView) findViewById(R.id.profilescreenname); userLocation = (TextView) findViewById(R.id.user_location); userUrl = (TextView) findViewById(R.id.user_url); userInfo = (TextView) findViewById(R.id.tweet_user_info); friendsCount = (TextView) findViewById(R.id.friends_count); followersCount = (TextView) findViewById(R.id.followers_count); TextView friendsCountTitle = (TextView) findViewById(R.id.friends_count_title); TextView followersCountTitle = (TextView) findViewById(R.id.followers_count_title); String who; if (userId.equals(myself)) { who = "我"; } else { who = "ta"; } friendsCountTitle.setText(MessageFormat.format( getString(R.string.profile_friends_count_title), who)); followersCountTitle.setText(MessageFormat.format( getString(R.string.profile_followers_count_title), who)); statusCount = (TextView) findViewById(R.id.statuses_count); favouritesCount = (TextView) findViewById(R.id.favourites_count); friendsLayout = (RelativeLayout) findViewById(R.id.friendsLayout); followersLayout = (LinearLayout) findViewById(R.id.followersLayout); statusesLayout = (LinearLayout) findViewById(R.id.statusesLayout); favouritesLayout = (LinearLayout) findViewById(R.id.favouritesLayout); isFollowingText = (TextView) findViewById(R.id.isfollowing_text); followingBtn = (Button) findViewById(R.id.following_btn); // 为按钮面板添加事件 friendsLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = FollowingActivity.createIntent(userId); intent.setClass(ProfileActivity.this, FollowingActivity.class); startActivity(intent); } }); followersLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Toast.makeText(getBaseContext(), "跟随他的人", // Toast.LENGTH_SHORT).show(); Intent intent = FollowersActivity.createIntent(userId); intent.setClass(ProfileActivity.this, FollowersActivity.class); startActivity(intent); } }); statusesLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //在没有得到profileInfo时,不允许点击事件生效 if(profileInfo == null) { return; } String showName; if (!Utils.isEmpty(profileInfo.getScreenName())) { showName = profileInfo.getScreenName(); } else { showName = profileInfo.getName(); } Intent intent = UserTimelineActivity.createIntent( profileInfo.getId(), showName); launchActivity(intent); } }); favouritesLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = FavoritesActivity.createIntent(userId); intent.setClass(ProfileActivity.this, FavoritesActivity.class); startActivity(intent); } }); // 刷新 View.OnClickListener refreshListener = new View.OnClickListener() { @Override public void onClick(View v) { doGetProfileInfo(); } }; refreshButton.setOnClickListener(refreshListener); } private void draw() { Log.i(TAG, "draw"); bindProfileInfo(); //doGetProfileInfo(); } @Override protected void onResume() { super.onResume(); Log.i(TAG, "onResume."); } @Override protected void onStart() { super.onStart(); Log.i(TAG, "onStart."); } @Override protected void onStop() { super.onStop(); Log.i(TAG, "onStop."); } /** * 从数据库获取,如果数据库不存在则创建 */ private void bindProfileInfo() { dialog=ProgressDialog.show(ProfileActivity.this, "请稍后", "正在加载信息..."); if (null != db && db.existsUser(userId)) { Cursor cursor = db.getUserInfoById(userId); profileInfo = User.parseUser(cursor); cursor.close(); if (profileInfo == null) { Log.w(TAG, "cannot get userinfo from userinfotable the id is" + userId); } bindControl(); if(dialog!=null){ dialog.dismiss(); } } else { doGetProfileInfo(); } } private void doGetProfileInfo() { // 旋转刷新按钮 animRotate(refreshButton); if (profileInfoTask != null && profileInfoTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { profileInfoTask = new GetProfileTask(); profileInfoTask.setListener(profileInfoTaskListener); TaskParams params = new TaskParams(); profileInfoTask.execute(params); } } private void bindControl() { if (profileInfo.getId().equals(myself)) { sendMentionBtn.setVisibility(View.GONE); sendDmBtn.setVisibility(View.GONE); } else { // 发送留言 sendMentionBtn.setVisibility(View.VISIBLE); sendMentionBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = WriteActivity.createNewTweetIntent(String .format("@%s ", profileInfo.getScreenName())); startActivity(intent); } }); // 发送私信 sendDmBtn.setVisibility(View.VISIBLE); sendDmBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = WriteDmActivity.createIntent(profileInfo .getId()); startActivity(intent); } }); } if (userId.equals(myself)) { setHeaderTitle("@" + profileInfo.getScreenName()); } profileImageView .setImageBitmap(TwitterApplication.mProfileImageCacheManager .get(profileInfo.getProfileImageURL().toString(), callback)); profileName.setText(profileInfo.getId()); profileScreenName.setText("@" + profileInfo.getScreenName()); if (profileInfo.getId().equals(myself)) { isFollowingText.setText(R.string.profile_isyou); followingBtn.setVisibility(View.GONE); } else if (profileInfo.isFollowing()) { isFollowingText.setText(R.string.profile_isfollowing); followingBtn.setVisibility(View.VISIBLE); followingBtn.setText(R.string.user_label_unfollow); followingBtn.setOnClickListener(cancelFollowingListener); } else { isFollowingText.setText(R.string.profile_notfollowing); followingBtn.setVisibility(View.VISIBLE); followingBtn.setText(R.string.user_label_follow); followingBtn.setOnClickListener(setfollowingListener); } String location = profileInfo.getLocation(); if (location == null || location.length() == 0) { location = getResources().getString(R.string.profile_location_null); } userLocation.setText(location); if (profileInfo.getURL() != null) { userUrl.setText(profileInfo.getURL().toString()); } else { userUrl.setText(FANFOUROOT + profileInfo.getId()); } String description = profileInfo.getDescription(); if (description == null || description.length() == 0) { description = getResources().getString( R.string.profile_description_null); } userInfo.setText(description); friendsCount.setText(String.valueOf(profileInfo.getFriendsCount())); followersCount.setText(String.valueOf(profileInfo.getFollowersCount())); statusCount.setText(String.valueOf(profileInfo.getStatusesCount())); favouritesCount .setText(String.valueOf(profileInfo.getFavouritesCount())); } private TaskListener profileInfoTaskListener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { refreshButton.clearAnimation(); // 加载成功 if (result == TaskResult.OK) { if (null != db && !db.existsUser(userId)) { com.ch_linghu.fanfoudroid.data.User userinfodb = profileInfo .parseUser(); db.createUserInfo(userinfodb); } else { // 更新用户 updateUser(); } // 绑定控件 bindControl(); if(dialog!=null){ dialog.dismiss(); } } } @Override public String getName() { return "GetProfileInfo"; } }; /** * 更新数据库中的用户 * * @return */ private boolean updateUser() { ContentValues args = new ContentValues(); args.put(BaseColumns._ID, profileInfo.getName()); args.put(UserInfoTable.FIELD_USER_NAME, profileInfo.getName()); args.put(UserInfoTable.FIELD_USER_SCREEN_NAME, profileInfo.getScreenName()); String location = profileInfo.getLocation(); args.put(UserInfoTable.FIELD_LOCALTION, location); String description = profileInfo.getDescription(); args.put(UserInfoTable.FIELD_DESCRIPTION, description); args.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, profileInfo.getProfileBackgroundImageUrl()); if (profileInfo.getURL() != null) { args.put(UserInfoTable.FIELD_URL, profileInfo.getURL().toString()); } args.put(UserInfoTable.FIELD_PROTECTED, profileInfo.isProtected()); args.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, profileInfo.getFollowersCount()); args.put(UserInfoTable.FIELD_LAST_STATUS, profileInfo.getStatusSource()); args.put(UserInfoTable.FIELD_FRIENDS_COUNT, profileInfo.getFriendsCount()); args.put(UserInfoTable.FIELD_FAVORITES_COUNT, profileInfo.getFavouritesCount()); args.put(UserInfoTable.FIELD_STATUSES_COUNT, profileInfo.getStatusesCount()); args.put(UserInfoTable.FIELD_FOLLOWING, profileInfo.isFollowing()); return db.updateUser(profileInfo.getId(), args); } /** * 获取用户信息task * * @author Dino * */ private class GetProfileTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { profileInfo = getApi().showUser(userId); } catch (HttpException e) { Log.e(TAG, e.getMessage()); return TaskResult.FAILED; } return TaskResult.OK; } } /** * 设置关注监听 */ private OnClickListener setfollowingListener = new OnClickListener() { @Override public void onClick(View v) { Builder diaBuilder = new AlertDialog.Builder(ProfileActivity.this) .setTitle("关注提示").setMessage("确实要添加关注吗?"); diaBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (setFollowingTask != null && setFollowingTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { setFollowingTask = new SetFollowingTask(); setFollowingTask .setListener(setFollowingTaskLinstener); TaskParams params = new TaskParams(); setFollowingTask.execute(params); } } }); diaBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); Dialog dialog = diaBuilder.create(); dialog.show(); } }; /* * 取消关注监听 */ private OnClickListener cancelFollowingListener = new OnClickListener() { @Override public void onClick(View v) { Builder diaBuilder = new AlertDialog.Builder(ProfileActivity.this) .setTitle("关注提示").setMessage("确实要取消关注吗?"); diaBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (cancelFollowingTask != null && cancelFollowingTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { cancelFollowingTask = new CancelFollowingTask(); cancelFollowingTask .setListener(cancelFollowingTaskLinstener); TaskParams params = new TaskParams(); cancelFollowingTask.execute(params); } } }); diaBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); Dialog dialog = diaBuilder.create(); dialog.show(); } }; /** * 设置关注 * * @author Dino * */ private class SetFollowingTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { getApi().createFriendship(userId); } catch (HttpException e) { Log.w(TAG, "create friend ship error"); return TaskResult.FAILED; } return TaskResult.OK; } } private TaskListener setFollowingTaskLinstener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { followingBtn.setText("取消关注"); isFollowingText.setText(getResources().getString( R.string.profile_isfollowing)); followingBtn.setOnClickListener(cancelFollowingListener); Toast.makeText(getBaseContext(), "关注成功", Toast.LENGTH_SHORT) .show(); } else if (result == TaskResult.FAILED) { Toast.makeText(getBaseContext(), "关注失败", Toast.LENGTH_SHORT) .show(); } } @Override public String getName() { // TODO Auto-generated method stub return null; } }; /** * 取消关注 * * @author Dino * */ private class CancelFollowingTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { getApi().destroyFriendship(userId); } catch (HttpException e) { Log.w(TAG, "create friend ship error"); return TaskResult.FAILED; } return TaskResult.OK; } } private TaskListener cancelFollowingTaskLinstener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { followingBtn.setText("添加关注"); isFollowingText.setText(getResources().getString( R.string.profile_notfollowing)); followingBtn.setOnClickListener(setfollowingListener); Toast.makeText(getBaseContext(), "取消关注成功", Toast.LENGTH_SHORT) .show(); } else if (result == TaskResult.FAILED) { Toast.makeText(getBaseContext(), "取消关注失败", Toast.LENGTH_SHORT) .show(); } } @Override public String getName() { // TODO Auto-generated method stub return null; } }; }
Java
package com.ch_linghu.fanfoudroid; import java.util.ArrayList; import java.util.HashSet; import android.app.SearchManager; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.widget.ListView; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.helper.Utils; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.base.TwitterListBaseActivity; import com.ch_linghu.fanfoudroid.ui.module.MyListView; import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter; import com.ch_linghu.fanfoudroid.ui.module.TweetArrayAdapter; import com.ch_linghu.fanfoudroid.weibo.Query; import com.ch_linghu.fanfoudroid.weibo.QueryResult; public class SearchResultActivity extends TwitterListBaseActivity implements MyListView.OnNeedMoreListener { private static final String TAG = "SearchActivity"; // Views. private MyListView mTweetList; // State. private String mSearchQuery; private ArrayList<Tweet> mTweets; private TweetArrayAdapter mAdapter; private int mNextPage = 1; private String mLastId = null; private static class State { State(SearchResultActivity activity) { mTweets = activity.mTweets; mNextPage = activity.mNextPage; } public ArrayList<Tweet> mTweets; public int mNextPage; } // Tasks. private GenericTask mSearchTask; private TaskListener mSearchTaskListener = new TaskAdapter(){ @Override public void onPreExecute(GenericTask task) { animRotate(refreshButton); if (mNextPage == 1) { updateProgress(getString(R.string.page_status_refreshing)); } else { updateProgress(getString(R.string.page_status_refreshing)); } } @Override public void onProgressUpdate(GenericTask task, Object param) { draw(); } @Override public void onPostExecute(GenericTask task, TaskResult result) { refreshButton.clearAnimation(); if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { draw(); } else { // Do nothing. } updateProgress(""); } @Override public String getName() { return "SearchTask"; } }; @Override protected boolean _onCreate(Bundle savedInstanceState) { if (super._onCreate(savedInstanceState)){ Intent intent = getIntent(); // Assume it's SEARCH. // String action = intent.getAction(); mSearchQuery = intent.getStringExtra(SearchManager.QUERY); if (TextUtils.isEmpty(mSearchQuery)) { mSearchQuery = intent.getData().getLastPathSegment(); } setHeaderTitle(mSearchQuery); setTitle(mSearchQuery); State state = (State) getLastNonConfigurationInstance(); if (state != null) { mTweets = state.mTweets; draw(); } else { doSearch(); } return true; }else{ return false; } } @Override protected int getLayoutId(){ return R.layout.main; } @Override protected void onResume() { super.onResume(); checkIsLogedIn(); } @Override public Object onRetainNonConfigurationInstance() { return createState(); } private synchronized State createState() { return new State(this); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } @Override protected void onDestroy() { Log.i(TAG, "onDestroy."); if (mSearchTask != null && mSearchTask.getStatus() == GenericTask.Status.RUNNING) { mSearchTask.cancel(true); } super.onDestroy(); } // UI helpers. private void updateProgress(String progress) { mProgressText.setText(progress); } private void draw() { mAdapter.refresh(mTweets); } private void doSearch() { Log.i(TAG, "Attempting search."); if (mSearchTask != null && mSearchTask.getStatus() == GenericTask.Status.RUNNING){ return; }else{ mSearchTask = new SearchTask(); mSearchTask.setListener(mSearchTaskListener); mSearchTask.execute(); } } private class SearchTask extends GenericTask { ArrayList<Tweet> mTweets = new ArrayList<Tweet>(); @Override protected TaskResult _doInBackground(TaskParams...params) { QueryResult result; try { Query query = new Query(mSearchQuery); if (!Utils.isEmpty(mLastId)){ query.setMaxId(mLastId); } result = getApi().search(query);//.search(mSearchQuery, mNextPage); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } HashSet<String> imageUrls = new HashSet<String>(); for (com.ch_linghu.fanfoudroid.weibo.Status status : result.getStatus()) { if (isCancelled()) { return TaskResult.CANCELLED; } Tweet tweet; tweet = Tweet.create(status); mLastId = tweet.id; mTweets.add(tweet); imageUrls.add(tweet.profileImageUrl); if (isCancelled()) { return TaskResult.CANCELLED; } } addTweets(mTweets); // if (isCancelled()) { // return TaskResult.CANCELLED; // } // // publishProgress(); // // // TODO: what if orientation change? // ImageManager imageManager = getImageManager(); // MemoryImageCache imageCache = new MemoryImageCache(); // // for (String imageUrl : imageUrls) { // if (!Utils.isEmpty(imageUrl)) { // // Fetch image to cache. // try { // Bitmap bitmap = imageManager.fetchImage(imageUrl); // imageCache.put(imageUrl, bitmap); // } catch (IOException e) { // Log.e(TAG, e.getMessage(), e); // } // } // // if (isCancelled()) { // return TaskResult.CANCELLED; // } // } // // addImages(imageCache); return TaskResult.OK; } } @Override public boolean onCreateOptionsMenu(Menu menu) { return super.onCreateOptionsMenu(menu); } @Override public void needMore() { if (!isLastPage()) { doSearch(); } } public boolean isLastPage() { return mNextPage == -1; } @Override protected void adapterRefresh() { mAdapter.refresh(mTweets); } private synchronized void addTweets(ArrayList<Tweet> tweets) { if (tweets.size() == 0) { mNextPage = -1; return; } mTweets.addAll(tweets); ++mNextPage; } @Override protected String getActivityTitle() { return mSearchQuery; } @Override protected Tweet getContextItemTweet(int position) { return (Tweet)mAdapter.getItem(position); } @Override protected TweetAdapter getTweetAdapter() { return mAdapter; } @Override protected ListView getTweetList() { return mTweetList; } @Override protected void updateTweet(Tweet tweet) { // TODO Simple and stupid implementation for (Tweet t : mTweets){ if (t.id.equals(tweet.id)){ t.favorited = tweet.favorited; break; } } } @Override protected boolean useBasicMenu() { return true; } @Override protected void setupState() { mTweets = new ArrayList<Tweet>(); mTweetList = (MyListView) findViewById(R.id.tweet_list); mAdapter = new TweetArrayAdapter(this); mTweetList.setAdapter(mAdapter); mTweetList.setOnNeedMoreListener(this); } @Override public void doRetrieve() { doSearch(); } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid.service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /** * This broadcast receiver is awoken after boot and registers the service that * checks for new tweets. */ public class BootReceiver extends BroadcastReceiver { private static final String TAG = "BootReceiver"; @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "Twitta BootReceiver is receiving."); if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { TwitterService.schedule(context); } } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid.service; import java.text.DateFormat; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import android.app.AlarmManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.PendingIntent.CanceledException; import android.app.Service; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.Handler; import android.os.IBinder; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.preference.PreferenceManager; import android.util.Log; import android.widget.RemoteViews; import com.ch_linghu.fanfoudroid.DmActivity; import com.ch_linghu.fanfoudroid.FanfouWidget; import com.ch_linghu.fanfoudroid.MentionActivity; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterActivity; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.data.Dm; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.data.db.StatusTable; import com.ch_linghu.fanfoudroid.data.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.helper.Preferences; import com.ch_linghu.fanfoudroid.helper.Utils; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.weibo.Paging; import com.ch_linghu.fanfoudroid.weibo.Weibo; public class TwitterService extends Service { private static final String TAG = "TwitterService"; private NotificationManager mNotificationManager; private ArrayList<Tweet> mNewTweets; private ArrayList<Tweet> mNewMentions; private ArrayList<Dm> mNewDms; private GenericTask mRetrieveTask; public String getUserId() { return TwitterApplication.getMyselfId(); } @Override public void onStart(Intent intent, int startId) { // fetchMessages(); // handler.postDelayed(mTask, 10000); super.onStart(intent, startId); } private TaskListener mRetrieveTaskListener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { SharedPreferences preferences = TwitterApplication.mPref; boolean needCheck = preferences.getBoolean(Preferences.CHECK_UPDATES_KEY, false); boolean timeline_only = preferences.getBoolean( Preferences.TIMELINE_ONLY_KEY, false); boolean replies_only = preferences.getBoolean( Preferences.REPLIES_ONLY_KEY, true); boolean dm_only = preferences.getBoolean(Preferences.DM_ONLY_KEY, true); if (needCheck){ if (timeline_only){ processNewTweets(); } if (replies_only){ processNewMentions(); } if (dm_only){ processNewDms(); } } } try { Intent intent = new Intent(TwitterService.this, FanfouWidget.class); intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); PendingIntent pi = PendingIntent.getBroadcast( TwitterService.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); pi.send(); } catch (CanceledException e) { Log.e(TAG, e.getMessage()); e.printStackTrace(); } stopSelf(); } @Override public String getName() { return "ServiceRetrieveTask"; } }; private WakeLock mWakeLock; @Override public IBinder onBind(Intent intent) { return null; } private TwitterDatabase getDb() { return TwitterApplication.mDb; } private Weibo getApi() { return TwitterApplication.mApi; } @Override public void onCreate() { super.onCreate(); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); mWakeLock.acquire(); boolean needCheck = TwitterApplication.mPref.getBoolean(Preferences.CHECK_UPDATES_KEY, false); boolean widgetIsEnabled = TwitterService.widgetIsEnabled; if (!needCheck && !widgetIsEnabled) { Log.i(TAG, "Check update preference is false."); stopSelf(); return; } if (!getApi().isLoggedIn()) { Log.i(TAG, "Not logged in."); stopSelf(); return; } schedule(TwitterService.this); mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); mNewTweets = new ArrayList<Tweet>(); mNewMentions = new ArrayList<Tweet>(); mNewDms = new ArrayList<Dm>(); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mRetrieveTask = new RetrieveTask(); mRetrieveTask.setListener(mRetrieveTaskListener); mRetrieveTask.execute((TaskParams[])null); } } private void processNewTweets() { int count = mNewTweets.size(); if (count <= 0) { return; } Tweet latestTweet = mNewTweets.get(0); String title; String text; if (count == 1) { title = latestTweet.screenName; text = Utils.getSimpleTweetText(latestTweet.text); } else { title = getString(R.string.service_new_twitter_updates); text = getString(R.string.service_x_new_tweets); text = MessageFormat.format(text, count); } PendingIntent intent = PendingIntent.getActivity(this, 0, TwitterActivity.createIntent(this), 0); notify(intent, TWEET_NOTIFICATION_ID, R.drawable.notify_tweet, Utils.getSimpleTweetText(latestTweet.text), title, text); } private void processNewMentions() { int count = mNewMentions.size(); if (count <= 0) { return; } Tweet latestTweet = mNewMentions.get(0); String title; String text; if (count == 1) { title = latestTweet.screenName; text = Utils.getSimpleTweetText(latestTweet.text); } else { title = getString(R.string.service_new_mention_updates); text = getString(R.string.service_x_new_mentions); text = MessageFormat.format(text, count); } PendingIntent intent = PendingIntent.getActivity(this, 0, MentionActivity.createIntent(this), 0); notify(intent, MENTION_NOTIFICATION_ID, R.drawable.notify_mention, Utils.getSimpleTweetText(latestTweet.text), title, text); } private static int TWEET_NOTIFICATION_ID = 0; private static int DM_NOTIFICATION_ID = 1; private static int MENTION_NOTIFICATION_ID = 2; private void notify(PendingIntent intent, int notificationId, int notifyIconId, String tickerText, String title, String text) { Notification notification = new Notification(notifyIconId, tickerText, System.currentTimeMillis()); notification.setLatestEventInfo(this, title, text, intent); notification.flags = Notification.FLAG_AUTO_CANCEL | Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_SHOW_LIGHTS; notification.ledARGB = 0xFF84E4FA; notification.ledOnMS = 5000; notification.ledOffMS = 5000; String ringtoneUri = TwitterApplication.mPref.getString(Preferences.RINGTONE_KEY, null); if (ringtoneUri == null) { notification.defaults |= Notification.DEFAULT_SOUND; } else { notification.sound = Uri.parse(ringtoneUri); } if (TwitterApplication.mPref.getBoolean(Preferences.VIBRATE_KEY, false)) { notification.defaults |= Notification.DEFAULT_VIBRATE; } mNotificationManager.notify(notificationId, notification); } private void processNewDms() { int count = mNewDms.size(); if (count <= 0) { return; } Dm latest = mNewDms.get(0); String title; String text; if (count == 1) { title = latest.screenName; text = Utils.getSimpleTweetText(latest.text); } else { title = getString(R.string.service_new_direct_message_updates); text = getString(R.string.service_x_new_direct_messages); text = MessageFormat.format(text, count); } PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, DmActivity.createIntent(), 0); notify(pendingIntent, DM_NOTIFICATION_ID, R.drawable.notify_dm, Utils.getSimpleTweetText(latest.text), title, text); } @Override public void onDestroy() { Log.i(TAG, "IM DYING!!!"); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { mRetrieveTask.cancel(true); } mWakeLock.release(); super.onDestroy(); } public static void schedule(Context context) { SharedPreferences preferences = TwitterApplication.mPref; boolean needCheck = preferences.getBoolean(Preferences.CHECK_UPDATES_KEY, false); boolean widgetIsEnabled = TwitterService.widgetIsEnabled; if (!needCheck && !widgetIsEnabled) { Log.i(TAG, "Check update preference is false."); return; } String intervalPref = preferences .getString( Preferences.CHECK_UPDATE_INTERVAL_KEY, context.getString(R.string.pref_check_updates_interval_default)); int interval = Integer.parseInt(intervalPref); //int interval = 1; //for debug Intent intent = new Intent(context, TwitterService.class); PendingIntent pending = PendingIntent.getService(context, 0, intent, 0); Calendar c = new GregorianCalendar(); c.add(Calendar.MINUTE, interval); DateFormat df = new SimpleDateFormat("h:mm a"); Log.i(TAG, "Scheduling alarm at " + df.format(c.getTime())); AlarmManager alarm = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); alarm.cancel(pending); if (needCheck){ alarm.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pending); }else{ //only for widget alarm.set(AlarmManager.RTC, c.getTimeInMillis(), pending); } } public static void unschedule(Context context) { Intent intent = new Intent(context, TwitterService.class); PendingIntent pending = PendingIntent.getService(context, 0, intent, 0); AlarmManager alarm = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); Log.i(TAG, "Cancelling alarms."); alarm.cancel(pending); } private static boolean widgetIsEnabled = false; public static void setWidgetStatus(boolean isEnabled){ widgetIsEnabled = isEnabled; } public static boolean isWidgetEnabled(){ return widgetIsEnabled; } private class RetrieveTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { SharedPreferences preferences = TwitterApplication.mPref; boolean timeline_only = preferences.getBoolean( Preferences.TIMELINE_ONLY_KEY, false); boolean replies_only = preferences.getBoolean( Preferences.REPLIES_ONLY_KEY, true); boolean dm_only = preferences.getBoolean(Preferences.DM_ONLY_KEY, true); Log.d(TAG, "TwitterIsEnabled? " + TwitterService.widgetIsEnabled); if (timeline_only || TwitterService.widgetIsEnabled) { String maxId = getDb() .fetchMaxTweetId(TwitterApplication.getMyselfId(), StatusTable.TYPE_HOME); Log.i(TAG, "Max id is:" + maxId); List<com.ch_linghu.fanfoudroid.weibo.Status> statusList; try { if (maxId != null) { statusList = getApi().getFriendsTimeline( new Paging(maxId)); } else { statusList = getApi().getFriendsTimeline(); } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } for (com.ch_linghu.fanfoudroid.weibo.Status status : statusList) { if (isCancelled()) { return TaskResult.CANCELLED; } Tweet tweet; tweet = Tweet.create(status); mNewTweets.add(tweet); Log.i(TAG, mNewTweets.size() + " new tweets."); int count = getDb().addNewTweetsAndCountUnread(mNewTweets, TwitterApplication.getMyselfId(), StatusTable.TYPE_HOME); if (count <= 0) { return TaskResult.FAILED; } } if (isCancelled()) { return TaskResult.CANCELLED; } } if (replies_only) { String maxMentionId = getDb().fetchMaxTweetId( TwitterApplication.getMyselfId(), StatusTable.TYPE_MENTION); Log.i(TAG, "Max mention id is:" + maxMentionId); List<com.ch_linghu.fanfoudroid.weibo.Status> statusList; try { if (maxMentionId != null) { statusList = getApi().getMentions( new Paging(maxMentionId)); } else { statusList = getApi().getMentions(); } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } for (com.ch_linghu.fanfoudroid.weibo.Status status : statusList) { if (isCancelled()) { return TaskResult.CANCELLED; } Tweet tweet; tweet = Tweet.create(status); mNewMentions.add(tweet); Log.i(TAG, mNewMentions.size() + " new mentions."); int count = getDb().addNewTweetsAndCountUnread(mNewMentions, TwitterApplication.getMyselfId(), StatusTable.TYPE_MENTION); if (count <= 0) { return TaskResult.FAILED; } } if (isCancelled()) { return TaskResult.CANCELLED; } } if (dm_only) { String maxId = getDb().fetchMaxDmId(false); Log.i(TAG, "Max DM id is:" + maxId); List<com.ch_linghu.fanfoudroid.weibo.DirectMessage> dmList; try { if (maxId != null) { dmList = getApi().getDirectMessages(new Paging(maxId)); } else { dmList = getApi().getDirectMessages(); } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } for (com.ch_linghu.fanfoudroid.weibo.DirectMessage directMessage : dmList) { if (isCancelled()) { return TaskResult.CANCELLED; } Dm dm; dm = Dm.create(directMessage, false); mNewDms.add(dm); Log.i(TAG, mNewDms.size() + " new DMs."); int count = 0; TwitterDatabase db = getDb(); if (db.fetchDmCount() > 0) { count = db.addNewDmsAndCountUnread(mNewDms); } else { Log.i(TAG, "No existing DMs. Don't notify."); db.addDms(mNewDms, false); } if (count <= 0) { return TaskResult.FAILED; } } if (isCancelled()) { return TaskResult.CANCELLED; } } return TaskResult.OK; } } }
Java
package com.ch_linghu.fanfoudroid.service; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import com.ch_linghu.fanfoudroid.FanfouWidget; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.data.db.StatusTable; import com.ch_linghu.fanfoudroid.data.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.helper.Preferences; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Handler; import android.os.IBinder; import android.util.Log; import android.widget.RemoteViews; public class WidgetService extends Service { protected static final String TAG = "WidgetService"; private int position = 0; private List<Tweet> tweets; private TwitterDatabase getDb() { return TwitterApplication.mDb; } public String getUserId() { return TwitterApplication.getMyselfId(); } private void fetchMessages() { if (tweets == null) { tweets = new ArrayList<Tweet>(); }else{ tweets.clear(); } Cursor cursor = getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_HOME); if (cursor != null) { if (cursor.moveToFirst()) { do { Tweet tweet = StatusTable.parseCursor(cursor); tweets.add(tweet); } while (cursor.moveToNext()); } } } public RemoteViews buildUpdate(Context context) { RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_initial_layout); updateViews .setTextViewText(R.id.status_text, tweets.get(position).text); //updateViews.setOnClickPendingIntent(viewId, pendingIntent) position++; return updateViews; } private Handler handler = new Handler(); private Runnable mTask = new Runnable() { @Override public void run() { Log.i(TAG, "tweets size="+tweets.size()+" position=" + position); if (position >= tweets.size()) { position = 0; } ComponentName fanfouWidget = new ComponentName(WidgetService.this, FanfouWidget.class); AppWidgetManager manager = AppWidgetManager .getInstance(getBaseContext()); manager.updateAppWidget(fanfouWidget, buildUpdate(WidgetService.this)); handler.postDelayed(mTask, 10000); } }; public static void schedule(Context context) { SharedPreferences preferences = TwitterApplication.mPref; if (!preferences.getBoolean(Preferences.CHECK_UPDATES_KEY, false)) { Log.i(TAG, "Check update preference is false."); return; } String intervalPref = preferences .getString( Preferences.CHECK_UPDATE_INTERVAL_KEY, context.getString(R.string.pref_check_updates_interval_default)); int interval = Integer.parseInt(intervalPref); Intent intent = new Intent(context, WidgetService.class); PendingIntent pending = PendingIntent.getService(context, 0, intent, 0); Calendar c = new GregorianCalendar(); c.add(Calendar.MINUTE, interval); DateFormat df = new SimpleDateFormat("h:mm a"); Log.i(TAG, "Scheduling alarm at " + df.format(c.getTime())); AlarmManager alarm = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); alarm.cancel(pending); alarm.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pending); } /** * @see android.app.Service#onBind(Intent) */ @Override public IBinder onBind(Intent intent) { // TODO Put your code here return null; } /** * @see android.app.Service#onCreate() */ @Override public void onCreate() { Log.i(TAG, "WidgetService onCreate"); schedule(WidgetService.this); } /** * @see android.app.Service#onStart(Intent,int) */ @Override public void onStart(Intent intent, int startId) { Log.i(TAG, "WidgetService onStart"); fetchMessages(); handler.removeCallbacks(mTask); handler.postDelayed(mTask, 10000); } @Override public void onDestroy() { Log.i(TAG, "WidgetService Stop "); handler.removeCallbacks(mTask);//当服务结束时,删除线程 super.onDestroy(); } }
Java
package com.ch_linghu.fanfoudroid.data; import com.ch_linghu.fanfoudroid.weibo.DirectMessage; import com.ch_linghu.fanfoudroid.weibo.User; import com.ch_linghu.fanfoudroid.helper.Utils; public class Dm extends Message { @SuppressWarnings("unused") private static final String TAG = "Dm"; public boolean isSent; public static Dm create(DirectMessage directMessage, boolean isSent){ Dm dm = new Dm(); dm.id = directMessage.getId(); dm.text = directMessage.getText(); dm.createdAt = directMessage.getCreatedAt(); dm.isSent = isSent; User user = dm.isSent ? directMessage.getRecipient() : directMessage.getSender(); dm.screenName = Utils.getSimpleTweetText(user.getScreenName()); dm.userId = user.getId(); dm.profileImageUrl = user.getProfileImageURL().toString(); return dm; } }
Java
package com.ch_linghu.fanfoudroid.data; import java.util.Date; import android.os.Parcel; import android.os.Parcelable; public class User implements Parcelable { public String id; public String name; public String screenName; public String location; public String description; public String profileImageUrl; public String url; public boolean isProtected; public int followersCount; public String lastStatus; public int friendsCount; public int favoritesCount; public int statusesCount; public Date createdAt; public boolean isFollowing; // public boolean notifications; // public utc_offset public User() {} public static User create(com.ch_linghu.fanfoudroid.weibo.User u) { User user = new User(); user.id = u.getId(); user.name = u.getName(); user.screenName = u.getScreenName(); user.location = u.getLocation(); user.description = u.getDescription(); user.profileImageUrl = u.getProfileImageURL().toString(); if (u.getURL() != null) { user.url = u.getURL().toString(); } user.isProtected = u.isProtected(); user.followersCount = u.getFollowersCount(); user.lastStatus = u.getStatusText(); user.friendsCount = u.getFriendsCount(); user.favoritesCount = u.getFavouritesCount(); user.statusesCount = u.getStatusesCount(); user.createdAt = u.getCreatedAt(); user.isFollowing = u.isFollowing(); return user; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel out, int flags) { boolean[] boolArray = new boolean[] { isProtected, isFollowing }; out.writeString(id); out.writeString(name); out.writeString(screenName); out.writeString(location); out.writeString(description); out.writeString(profileImageUrl); out.writeString(url); out.writeBooleanArray(boolArray); out.writeInt(friendsCount); out.writeInt(followersCount); out.writeInt(statusesCount); } public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() { public User createFromParcel(Parcel in) { return new User(in); } public User[] newArray(int size) { // return new User[size]; throw new UnsupportedOperationException(); } }; public User(Parcel in){ boolean[] boolArray = new boolean[]{isProtected, isFollowing}; id = in.readString(); name = in.readString(); screenName = in.readString(); location = in.readString(); description = in.readString(); profileImageUrl = in.readString(); url = in.readString(); in.readBooleanArray(boolArray); friendsCount = in.readInt(); followersCount = in.readInt(); statusesCount = in.readInt(); isProtected = boolArray[0]; isFollowing = boolArray[1]; } }
Java
package com.ch_linghu.fanfoudroid.data; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.data.db.StatusTable; import com.ch_linghu.fanfoudroid.data.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.helper.Utils; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.Response; import com.ch_linghu.fanfoudroid.weibo.Photo; import com.ch_linghu.fanfoudroid.weibo.RetweetDetails; import com.ch_linghu.fanfoudroid.weibo.User; import com.ch_linghu.fanfoudroid.weibo.Weibo; public class FanStatus extends Object<FanStatus> implements BaseContent { private static final String TAG = "FanStatus"; private static final long serialVersionUID = 1608000492860584608L; private Date createdAt; private String id; private String text; private String source; private boolean isTruncated; private String inReplyToStatusId; private String inReplyToUserId; private boolean isFavorited; private String inReplyToScreenName; private double latitude = -1; private double longitude = -1; private String thumbnail_pic; private String bmiddle_pic; private String original_pic; private String photo_url; private RetweetDetails retweetDetails; private User user = null; private int statusType = -1; // @see StatusTable#TYPE_* private boolean isDirty = false; // 是否被修改 public FanStatus(Response res, Weibo weibo) throws HttpException { super(res); Element elem = res.asDocument().getDocumentElement(); init(res, elem, weibo); } public FanStatus(Response res, Element elem, Weibo weibo) throws HttpException { super(res); init(res, elem, weibo); } public FanStatus(Response res)throws HttpException{ super(res); JSONObject json=res.asJSONObject(); try { id = json.getString("id"); text = json.getString("text"); source = json.getString("source"); createdAt = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy"); inReplyToStatusId = getString("in_reply_to_status_id", json); inReplyToUserId = getString("in_reply_to_user_id", json); isFavorited = getBoolean("favorited", json); // System.out.println("json photo" + json.getJSONObject("photo")); if(!json.isNull("photo")) { // System.out.println("not null" + json.getJSONObject("photo")); Photo photo = new Photo(json.getJSONObject("photo")); thumbnail_pic = photo.getThumbnail_pic(); bmiddle_pic = photo.getBmiddle_pic(); original_pic = photo.getOriginal_pic(); } else { // System.out.println("Null"); thumbnail_pic = ""; bmiddle_pic = ""; original_pic = ""; } if(!json.isNull("user")) user = new User(json.getJSONObject("user")); inReplyToScreenName=json.getString("in_reply_to_screen_name"); if(!json.isNull("retweetDetails")){ retweetDetails = new RetweetDetails(json.getJSONObject("retweetDetails")); } } catch (JSONException je) { throw new HttpException(je.getMessage() + ":" + json.toString(), je); } } /* modify by sycheng add some field*/ public FanStatus(JSONObject json)throws HttpException, JSONException{ id = json.getString("id"); text = json.getString("text"); source = json.getString("source"); createdAt = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy"); isFavorited = getBoolean("favorited", json); isTruncated=getBoolean("truncated", json); inReplyToStatusId = getString("in_reply_to_status_id", json); inReplyToUserId = getString("in_reply_to_user_id", json); inReplyToScreenName=json.getString("in_reply_to_screen_name"); if(!json.isNull("photo")) { Photo photo = new Photo(json.getJSONObject("photo")); thumbnail_pic = photo.getThumbnail_pic(); bmiddle_pic = photo.getBmiddle_pic(); original_pic = photo.getOriginal_pic(); } else { thumbnail_pic = ""; bmiddle_pic = ""; original_pic = ""; } user = new User(json.getJSONObject("user")); } public FanStatus(String str) throws HttpException, JSONException { // StatusStream uses this constructor super(); JSONObject json = new JSONObject(str); id = json.getString("id"); text = json.getString("text"); source = json.getString("source"); createdAt = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy"); inReplyToStatusId = getString("in_reply_to_status_id", json); inReplyToUserId = getString("in_reply_to_user_id", json); isFavorited = getBoolean("favorited", json); if(!json.isNull("photo")) { Photo photo = new Photo(json.getJSONObject("photo")); thumbnail_pic = photo.getThumbnail_pic(); bmiddle_pic = photo.getBmiddle_pic(); original_pic = photo.getOriginal_pic(); } else { thumbnail_pic = ""; bmiddle_pic = ""; original_pic = ""; } user = new User(json.getJSONObject("user")); } private void init(Response res, Element elem, Weibo weibo) throws HttpException { ensureRootNodeNameIs("status", elem); user = new User(res, (Element) elem.getElementsByTagName("user").item(0) , weibo); id = getChildString("id", elem); text = getChildText("text", elem); source = getChildText("source", elem); createdAt = getChildDate("created_at", elem); isTruncated = getChildBoolean("truncated", elem); inReplyToStatusId = getChildString("in_reply_to_status_id", elem); inReplyToUserId = getChildString("in_reply_to_user_id", elem); isFavorited = getChildBoolean("favorited", elem); inReplyToScreenName = getChildText("in_reply_to_screen_name", elem); NodeList georssPoint = elem.getElementsByTagName("georss:point"); if(1 == georssPoint.getLength()){ String[] point = georssPoint.item(0).getFirstChild().getNodeValue().split(" "); if(!"null".equals(point[0])) latitude = Double.parseDouble(point[0]); if(!"null".equals(point[1])) longitude = Double.parseDouble(point[1]); } NodeList retweetDetailsNode = elem.getElementsByTagName("retweet_details"); if(1 == retweetDetailsNode.getLength()){ retweetDetails = new RetweetDetails(res,(Element)retweetDetailsNode.item(0),weibo); } } /** * Return the created_at * * @return created_at * @since Weibo4J 1.1.0 */ public Date getCreatedAt() { return this.createdAt; } /** * Returns the id of the status * * @return the id */ public String getId() { return this.id; } /** * Returns the text of the status * * @return the text */ public String getText() { return this.text; } /** * Returns the source * * @return the source * @since Weibo4J 1.0.4 */ public String getSource() { return this.source; } /** * Test if the status is truncated * * @return true if truncated * @since Weibo4J 1.0.4 */ public boolean isTruncated() { return isTruncated; } /** * Returns the in_reply_tostatus_id * * @return the in_reply_tostatus_id * @since Weibo4J 1.0.4 */ public String getInReplyToStatusId() { return inReplyToStatusId; } /** * Returns the in_reply_user_id * * @return the in_reply_tostatus_id * @since Weibo4J 1.0.4 */ public String getInReplyToUserId() { return inReplyToUserId; } /** * Returns the in_reply_to_screen_name * * @return the in_in_reply_to_screen_name * @since Weibo4J 2.0.4 */ public String getInReplyToScreenName() { return inReplyToScreenName; } /** * returns The location's latitude that this tweet refers to. * * @since Weibo4J 2.0.10 */ public double getLatitude() { return latitude; } /** * returns The location's longitude that this tweet refers to. * * @since Weibo4J 2.0.10 */ public double getLongitude() { return longitude; } /** * Test if the status is favorited * * @return true if favorited * @since Weibo4J 1.0.4 */ public boolean isFavorited() { return isFavorited; } public String getThumbnail_pic() { return thumbnail_pic; } public String getBmiddle_pic() { return bmiddle_pic; } public String getOriginal_pic() { return original_pic; } /** * Return the user * * @return the user */ public User getUser() { return user; } // TODO: 等合并Tweet, FanStatus public int getType() { return -1111111; } /** * * @since Weibo4J 2.0.10 */ public boolean isRetweet(){ return null != retweetDetails; } /** * * @since Weibo4J 2.0.10 */ public RetweetDetails getRetweetDetails() { return retweetDetails; } public void setStatusType(int type) { statusType = type; } public int getStatusType() { return statusType; } /*package*/ static List<FanStatus> constructStatuses(Response res, Weibo weibo) throws HttpException { Document doc = res.asDocument(); if (isRootNodeNilClasses(doc)) { return new ArrayList<FanStatus>(0); } else { try { ensureRootNodeNameIs("statuses", doc); NodeList list = doc.getDocumentElement().getElementsByTagName( "status"); int size = list.getLength(); List<FanStatus> statuses = new ArrayList<FanStatus>(size); for (int i = 0; i < size; i++) { Element status = (Element) list.item(i); statuses.add(new FanStatus(res, status, weibo)); } return statuses; } catch (HttpException te) { ensureRootNodeNameIs("nil-classes", doc); return new ArrayList<FanStatus>(0); } } } /*modify by sycheng add json call method*/ /*package*/ static List<FanStatus> constructStatuses(Response res) throws HttpException { try { JSONArray list = res.asJSONArray(); int size = list.length(); List<FanStatus> statuses = new ArrayList<FanStatus>(size); for (int i = 0; i < size; i++) { statuses.add(new FanStatus(list.getJSONObject(i))); } return statuses; } catch (JSONException jsone) { throw new HttpException(jsone); } catch (HttpException te) { throw te; } } @Override public int hashCode() { return id.hashCode(); } public boolean equals(Object obj) { if (null == obj) { return false; } if (this == obj) { return true; } // return obj instanceof FanStatus && ((FanStatus) obj).id == this.id; return obj instanceof FanStatus && this.id.equals(((FanStatus) obj).id); } @Override public String toString() { return "FanStatus{" + "createdAt=" + createdAt + ", id=" + id + ", text='" + text + '\'' + ", source='" + source + '\'' + ", isTruncated=" + isTruncated + ", inReplyToStatusId=" + inReplyToStatusId + ", inReplyToUserId=" + inReplyToUserId + ", isFavorited=" + isFavorited + ", thumbnail_pic=" + thumbnail_pic + ", bmiddle_pic=" + bmiddle_pic + ", original_pic=" + original_pic + ", inReplyToScreenName='" + inReplyToScreenName + '\'' + ", latitude=" + latitude + ", longitude=" + longitude + ", retweetDetails=" + retweetDetails + ", user=" + user + '}'; } public boolean isEmpty() { return (null == id); } // Old Tweet public static String buildMetaText(StringBuilder builder, Date createdAt, String source, String replyTo) { builder.setLength(0); builder.append(Utils.getRelativeDate(createdAt)); builder.append(" "); builder.append(TwitterApplication.mContext.getString(R.string.tweet_source_prefix)); builder.append(source); if (!Utils.isEmpty(replyTo)) { builder.append(" " + TwitterApplication.mContext.getString(R.string.tweet_reply_to_prefix)); builder.append(replyTo); builder.append(TwitterApplication.mContext.getString(R.string.tweet_reply_to_suffix)); } return builder.toString(); } // Database /** * 向Status表中写入一行数据, 此方法为私有方法, 外部插入数据请使用 putTweets() * * @param tweet * 需要写入的单条消息 * @return the row ID of the newly inserted row, or -1 if an error occurred */ @Override public long insert() { SQLiteDatabase Db = TwitterDatabase.getDb(true); ContentValues values = this.toContentValues(); if (isExists(values.getAsString("id"), values.getAsString("user_id"), values.getAsInteger("type"))) { Log.i(TAG, values.get("id") + "is exists."); return -1; } long id = Db.insert(StatusTable.TABLE_NAME, null, values); if (-1 == id) { Log.e(TAG, "cann't insert the status : " + values.toString()); } else { Log.i(TAG, "Insert a status into datebase : " + values.toString()); } return id; } /** * 删除一条消息 * * @param tweetId * @param type -1 means all types * @return the number of rows affected if a whereClause is passed in, 0 * otherwise. To remove all rows and get a count pass "1" as the * whereClause. */ @Override public int delete() { SQLiteDatabase db = TwitterDatabase.getDb(true); String where = StatusTable._ID + " =? " + " AND " + StatusTable.FIELD_OWNER_ID + " = '" + user.getId() + "' "; if (-1 != statusType) { where += " AND " + StatusTable.FIELD_STATUS_TYPE + " = " + statusType; } return db.delete(StatusTable.TABLE_NAME, where, new String[] { id }); } @Override /** * 更新一条消息 * * @param tweetId * @param values * ContentValues 需要更新字段的键值对 * @return the number of rows affected, return -1 when no need to update */ public int update() { if (isDirty) { Log.i(TAG, "Update Tweet : " + id + " " + toString()); SQLiteDatabase Db = TwitterDatabase.getDb(true); return Db.update(StatusTable.TABLE_NAME, toContentValues(), // new Values StatusTable._ID + "=?", new String[] { id }); } return -1; } @Override public Cursor select() { // TODO Auto-generated method stub return null; } /** * 快速检查某条消息是否存在(指定类型) * * @param tweetId * @param type * <li>StatusTable.TYPE_HOME</li> * <li>StatusTable.TYPE_MENTION</li> * <li>StatusTable.TYPE_USER</li> * <li>StatusTable.TYPE_FAVORITE</li> * @return is exists */ public boolean isExists(String tweetId, String owner, int type) { SQLiteDatabase Db = TwitterDatabase.getDb(true); boolean result = false; Cursor cursor = Db.query(StatusTable.TABLE_NAME, new String[] { StatusTable._ID }, StatusTable._ID + " =? AND " + StatusTable.FIELD_OWNER_ID + "=? AND " + StatusTable.FIELD_STATUS_TYPE + " = " + type, new String[] { tweetId, owner }, null, null, null); if (cursor != null && cursor.getCount() > 0) { result = true; } cursor.close(); return result; } // TODO: 考虑是否可以通过使用转换为 ContentValues 来替代Parcelable public ContentValues toContentValues() { ContentValues values = new ContentValues(); return values; } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid.data; import java.util.Date; import org.json.JSONException; import org.json.JSONObject; import android.os.Parcel; import android.os.Parcelable; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.helper.Utils; import com.ch_linghu.fanfoudroid.weibo.Status; public class Tweet extends Message implements Parcelable { private static final String TAG = "Tweet"; public com.ch_linghu.fanfoudroid.weibo.User user; public String source; public String prevId; private int statusType = -1; // @see StatusTable#TYPE_* public void setStatusType(int type) { statusType = type; } public int getStatusType() { return statusType; } public Tweet(){} public static Tweet create(Status status){ Tweet tweet = new Tweet(); tweet.id = status.getId(); //转义符放到getSimpleTweetText里去处理,这里不做处理 tweet.text = status.getText(); tweet.createdAt = status.getCreatedAt(); tweet.favorited = status.isFavorited()?"true":"false"; tweet.truncated = status.isTruncated()?"true":"false"; tweet.inReplyToStatusId = status.getInReplyToStatusId(); tweet.inReplyToUserId = status.getInReplyToUserId(); tweet.inReplyToScreenName = status.getInReplyToScreenName(); tweet.screenName = Utils.getSimpleTweetText(status.getUser().getScreenName()); tweet.profileImageUrl = status.getUser().getProfileImageURL().toString(); tweet.userId = status.getUser().getId(); tweet.user = status.getUser(); tweet.thumbnail_pic = status.getThumbnail_pic(); tweet.bmiddle_pic = status.getBmiddle_pic(); tweet.original_pic = status.getOriginal_pic(); tweet.source = Utils.getSimpleTweetText(status.getSource()); return tweet; } public static Tweet createFromSearchApi(JSONObject jsonObject) throws JSONException { Tweet tweet = new Tweet(); tweet.id = jsonObject.getString("id") + ""; //转义符放到getSimpleTweetText里去处理,这里不做处理 tweet.text = jsonObject.getString("text"); tweet.createdAt = Utils.parseSearchApiDateTime(jsonObject.getString("created_at")); tweet.favorited = jsonObject.getString("favorited"); tweet.truncated = jsonObject.getString("truncated"); tweet.inReplyToStatusId = jsonObject.getString("in_reply_to_status_id"); tweet.inReplyToUserId = jsonObject.getString("in_reply_to_user_id"); tweet.inReplyToScreenName = jsonObject.getString("in_reply_to_screen_name"); tweet.screenName = Utils.getSimpleTweetText(jsonObject.getString("from_user")); tweet.profileImageUrl = jsonObject.getString("profile_image_url"); tweet.userId = jsonObject.getString("from_user_id"); tweet.source = Utils.getSimpleTweetText(jsonObject.getString("source")); return tweet; } public static String buildMetaText(StringBuilder builder, Date createdAt, String source, String replyTo) { builder.setLength(0); builder.append(Utils.getRelativeDate(createdAt)); builder.append(" "); builder.append(TwitterApplication.mContext.getString(R.string.tweet_source_prefix)); builder.append(source); if (!Utils.isEmpty(replyTo)) { builder.append(" " + TwitterApplication.mContext.getString(R.string.tweet_reply_to_prefix)); builder.append(replyTo); builder.append(TwitterApplication.mContext.getString(R.string.tweet_reply_to_suffix)); } return builder.toString(); } // For interface Parcelable public int describeContents() { return 0; } public void writeToParcel(Parcel out, int flags) { out.writeString(id); out.writeString(text); out.writeValue(createdAt); //Date out.writeString(screenName); out.writeString(favorited); out.writeString(inReplyToStatusId); out.writeString(inReplyToUserId); out.writeString(inReplyToScreenName); out.writeString(screenName); out.writeString(profileImageUrl); out.writeString(thumbnail_pic); out.writeString(bmiddle_pic); out.writeString(original_pic); out.writeString(userId); out.writeString(source); } public static final Parcelable.Creator<Tweet> CREATOR = new Parcelable.Creator<Tweet>() { public Tweet createFromParcel(Parcel in) { return new Tweet(in); } public Tweet[] newArray(int size) { // return new Tweet[size]; throw new UnsupportedOperationException(); } }; public Tweet(Parcel in) { id = in.readString(); text = in.readString(); createdAt = (Date) in.readValue(Date.class.getClassLoader()); screenName = in.readString(); favorited = in.readString(); inReplyToStatusId = in.readString(); inReplyToUserId = in.readString(); inReplyToScreenName = in.readString(); screenName = in.readString(); profileImageUrl = in.readString(); thumbnail_pic = in.readString(); bmiddle_pic = in.readString(); original_pic = in.readString(); userId = in.readString(); source = in.readString(); } @Override public String toString() { return "Tweet [source=" + source + ", id=" + id + ", screenName=" + screenName + ", text=" + text + ", profileImageUrl=" + profileImageUrl + ", createdAt=" + createdAt + ", userId=" + userId + ", favorited=" + favorited + ", inReplyToStatusId=" + inReplyToStatusId + ", inReplyToUserId=" + inReplyToUserId + ", inReplyToScreenName=" + inReplyToScreenName + "]"; } }
Java
package com.ch_linghu.fanfoudroid.data; import java.util.Date; public class Message { public String id; public String screenName; public String text; public String profileImageUrl; public Date createdAt; public String userId; public String favorited; public String truncated; public String inReplyToStatusId; public String inReplyToUserId; public String inReplyToScreenName; public String thumbnail_pic; public String bmiddle_pic; public String original_pic; }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid.data.db; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Locale; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.ch_linghu.fanfoudroid.data.Dm; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.helper.Utils; /** * @deprecated 已废弃 * */ public class TwitterDbAdapter { private static final String TAG = "TwitterDbAdapter"; public static final String TABLE_TWEET = "tweets"; public static final String TABLE_MENTION = "mentions"; public static final String TABLE_FAVORITE = "favorites"; public static final String TABLE_DIRECTMESSAGE = "dms"; public static final String TABLE_FOLLOWER = "followers"; public static final String KEY_ID = "_id"; public static final String KEY_USER = "user"; public static final String KEY_TEXT = "text"; public static final String KEY_FAVORITED = "favorited"; public static final String KEY_IN_REPLY_TO_STATUS_ID = "in_reply_to_status_id"; public static final String KEY_IN_REPLY_TO_USER_ID = "in_reply_to_user_id"; public static final String KEY_IN_REPLY_TO_SCREEN_NAME = "in_reply_to_screen_name"; public static final String KEY_PROFILE_IMAGE_URL = "profile_image_url"; public static final String KEY_IS_UNREAD = "is_unread"; public static final String KEY_CREATED_AT = "created_at"; public static final String KEY_SOURCE = "source"; public static final String KEY_IS_SENT = "is_sent"; public static final String KEY_USER_ID = "user_id"; //public static final String KEY_IS_REPLY = "is_reply"; public static final String KEY_PREV_ID = "prev_id"; public static final String[] TWEET_COLUMNS = new String[] { KEY_ID, KEY_USER, KEY_TEXT, KEY_PROFILE_IMAGE_URL, KEY_IS_UNREAD, KEY_CREATED_AT, KEY_FAVORITED, KEY_IN_REPLY_TO_STATUS_ID, KEY_IN_REPLY_TO_USER_ID, KEY_IN_REPLY_TO_SCREEN_NAME, KEY_SOURCE, KEY_USER_ID, KEY_PREV_ID }; public static final String[] DM_COLUMNS = new String[] { KEY_ID, KEY_USER, KEY_TEXT, KEY_PROFILE_IMAGE_URL, KEY_IS_UNREAD, KEY_IS_SENT, KEY_CREATED_AT, KEY_USER_ID }; public static final String[] FOLLOWER_COLUMNS = new String[] { KEY_ID }; private DatabaseHelper mDbHelper; private SQLiteDatabase mDb; private static final String DATABASE_NAME = "data"; private static final int DATABASE_VERSION = 2; // NOTE: the twitter ID is used as the row ID. // Furthermore, if a row already exists, an insert will replace // the old row upon conflict. private static final String TWEET_TABLE_CREATE = "create table " + TABLE_TWEET + " (" + KEY_ID + " text primary key on conflict replace, " + KEY_USER + " text not null, " + KEY_TEXT + " text not null, " + KEY_PROFILE_IMAGE_URL + " text not null, " + KEY_IS_UNREAD + " boolean not null, " + KEY_CREATED_AT + " date not null, " + KEY_FAVORITED + " text, " + KEY_IN_REPLY_TO_STATUS_ID + " text, " + KEY_IN_REPLY_TO_USER_ID + " text, " + KEY_IN_REPLY_TO_SCREEN_NAME + " text, " + KEY_SOURCE + " text not null, " + KEY_USER_ID + " text, " + KEY_PREV_ID + " text)"; private static final String MENTION_TABLE_CREATE = "create table " + TABLE_MENTION + " (" + KEY_ID + " text primary key on conflict replace, " + KEY_USER + " text not null, " + KEY_TEXT + " text not null, " + KEY_PROFILE_IMAGE_URL + " text not null, " + KEY_IS_UNREAD + " boolean not null, " + KEY_CREATED_AT + " date not null, " + KEY_FAVORITED + " text, " + KEY_IN_REPLY_TO_STATUS_ID + " text, " + KEY_IN_REPLY_TO_USER_ID + " text, " + KEY_IN_REPLY_TO_SCREEN_NAME + " text, " + KEY_SOURCE + " text not null, " + KEY_USER_ID + " text, " + KEY_PREV_ID + " text)"; private static final String FAVORITE_TABLE_CREATE = "create table " + TABLE_FAVORITE + " (" + KEY_ID + " text primary key on conflict replace, " + KEY_USER + " text not null, " + KEY_TEXT + " text not null, " + KEY_PROFILE_IMAGE_URL + " text not null, " + KEY_IS_UNREAD + " boolean not null, " + KEY_CREATED_AT + " date not null, " + KEY_FAVORITED + " text, " + KEY_IN_REPLY_TO_STATUS_ID + " text, " + KEY_IN_REPLY_TO_USER_ID + " text, " + KEY_IN_REPLY_TO_SCREEN_NAME + " text, " + KEY_SOURCE + " text not null, " + KEY_USER_ID + " text, " + KEY_PREV_ID + " text)"; private static final String DM_TABLE_CREATE = "create table " + TABLE_DIRECTMESSAGE + " (" + KEY_ID + " text primary key on conflict replace, " + KEY_USER + " text not null, " + KEY_TEXT + " text not null, " + KEY_PROFILE_IMAGE_URL + " text not null, " + KEY_IS_UNREAD + " boolean not null, " + KEY_IS_SENT + " boolean not null, " + KEY_CREATED_AT + " date not null, " + KEY_USER_ID + " text)"; private static final String FOLLOWER_TABLE_CREATE = "create table " + TABLE_FOLLOWER + " (" + KEY_ID + " text primary key on conflict replace)"; private final Context mContext; private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(TWEET_TABLE_CREATE); db.execSQL(MENTION_TABLE_CREATE); db.execSQL(FAVORITE_TABLE_CREATE); db.execSQL(DM_TABLE_CREATE); db.execSQL(FOLLOWER_TABLE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + " which destroys all old data"); db.execSQL("DROP TABLE IF EXISTS " + TABLE_TWEET); db.execSQL("DROP TABLE IF EXISTS " + TABLE_MENTION); db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITE); db.execSQL("DROP TABLE IF EXISTS " + TABLE_DIRECTMESSAGE); db.execSQL("DROP TABLE IF EXISTS " + TABLE_FOLLOWER); onCreate(db); } } public TwitterDbAdapter(Context context) { this.mContext = context; } public TwitterDbAdapter open() throws SQLException { mDbHelper = new DatabaseHelper(mContext); mDb = mDbHelper.getWritableDatabase(); return this; } public void close() { mDbHelper.close(); } public void resetDatabase(){ mDbHelper.onUpgrade(mDb, 1, 2); } public final static DateFormat DB_DATE_FORMATTER = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US); // TODO: move all these to the model. public long createTweet(String tableName, Tweet tweet, String prevId, boolean isUnread) { Log.d(TAG, "Insert tweet to table " + tableName + " : " + tweet.toString()); ContentValues initialValues = new ContentValues(); initialValues.put(KEY_ID, tweet.id); initialValues.put(KEY_USER, tweet.screenName); initialValues.put(KEY_TEXT, tweet.text); initialValues.put(KEY_PROFILE_IMAGE_URL, tweet.profileImageUrl); initialValues.put(KEY_FAVORITED, tweet.favorited); initialValues.put(KEY_IN_REPLY_TO_STATUS_ID, tweet.inReplyToStatusId); initialValues.put(KEY_IN_REPLY_TO_USER_ID, tweet.inReplyToUserId); initialValues.put(KEY_IN_REPLY_TO_SCREEN_NAME, tweet.inReplyToScreenName); initialValues.put(KEY_IS_UNREAD, isUnread); //initialValues.put(KEY_IS_REPLY, tweet.isReply()); if (!Utils.isEmpty(prevId)){ initialValues.put(KEY_PREV_ID, prevId); } initialValues .put(KEY_CREATED_AT, DB_DATE_FORMATTER.format(tweet.createdAt)); initialValues.put(KEY_SOURCE, tweet.source); initialValues.put(KEY_USER_ID, tweet.userId); //如果已经存在就更新,否则插入 if (isTweetExists(tableName, tweet.id)){ Log.d(TAG, String.format("[update]tweet.id=%s", tweet.id)); return mDb.update(tableName, initialValues, KEY_ID+"=?", new String[]{tweet.id}); }else{ Log.d(TAG, String.format("[insert]tweet.id=%s", tweet.id)); return mDb.insert(tableName, null, initialValues); } } public long updateTweet(String tableName, Tweet tweet){ String id = tweet.id; ContentValues initialValues = new ContentValues(); initialValues.put(KEY_ID, tweet.id); initialValues.put(KEY_USER, tweet.screenName); initialValues.put(KEY_TEXT, tweet.text); initialValues.put(KEY_PROFILE_IMAGE_URL, tweet.profileImageUrl); initialValues.put(KEY_FAVORITED, tweet.favorited); initialValues.put(KEY_IN_REPLY_TO_STATUS_ID, tweet.inReplyToStatusId); initialValues.put(KEY_IN_REPLY_TO_USER_ID, tweet.inReplyToUserId); initialValues.put(KEY_IN_REPLY_TO_SCREEN_NAME, tweet.inReplyToScreenName); //initialValues.put(KEY_IS_REPLY, tweet.isReply()); initialValues .put(KEY_CREATED_AT, DB_DATE_FORMATTER.format(tweet.createdAt)); initialValues.put(KEY_SOURCE, tweet.source); initialValues.put(KEY_USER_ID, tweet.userId); return mDb.update(tableName, initialValues, KEY_ID+"=?", new String[]{id}); } public boolean destoryStatus(String tableName, String status_id) { String where = KEY_ID + "='" + status_id + "'"; return mDb.delete(tableName, where , null) > 0; } public long createDm(Dm dm, boolean isUnread) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_ID, dm.id); initialValues.put(KEY_USER, dm.screenName); initialValues.put(KEY_TEXT, dm.text); initialValues.put(KEY_PROFILE_IMAGE_URL, dm.profileImageUrl); initialValues.put(KEY_IS_UNREAD, isUnread); initialValues.put(KEY_IS_SENT, dm.isSent); initialValues.put(KEY_CREATED_AT, DB_DATE_FORMATTER.format(dm.createdAt)); initialValues.put(KEY_USER_ID, dm.userId); return mDb.insert(TABLE_DIRECTMESSAGE, null, initialValues); } public long createFollower(String userId) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_ID, userId); return mDb.insert(TABLE_FOLLOWER, null, initialValues); } public void syncFollowers(List<String> followers) { try { mDb.beginTransaction(); deleteAllFollowers(); for (String userId : followers) { createFollower(userId); } mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } } public int addNewTweetsAndCountUnread(String tableName, List<Tweet> tweets) { addTweets(tableName, tweets, true); return fetchUnreadCount(tableName); } public Cursor fetchAllTweets(String tableName) { return mDb.query(tableName, TWEET_COLUMNS, null, null, null, null, KEY_CREATED_AT + " DESC"); } public Cursor fetchAllDms() { return mDb.query(TABLE_DIRECTMESSAGE, DM_COLUMNS, null, null, null, null, KEY_CREATED_AT + " DESC"); } public Cursor fetchInboxDms() { return mDb.query(TABLE_DIRECTMESSAGE, DM_COLUMNS, KEY_IS_SENT + " = ?", new String[]{"0"}, null, null, KEY_CREATED_AT + " DESC"); } public Cursor fetchSendboxDms() { return mDb.query(TABLE_DIRECTMESSAGE, DM_COLUMNS, KEY_IS_SENT + " = ?", new String[]{"1"}, null, null, KEY_CREATED_AT + " DESC"); } public Cursor fetchAllFollowers() { return mDb.query(TABLE_FOLLOWER, FOLLOWER_COLUMNS, null, null, null, null, null); } public Cursor getFollowerUsernames(String filter) { String likeFilter = '%' + filter + '%'; // TODO: clean this up. return mDb .rawQuery( "SELECT user_id AS _id, user FROM (SELECT user_id, user FROM tweets INNER JOIN followers on tweets.user_id = followers._id UNION SELECT user_id, user FROM dms INNER JOIN followers on dms.user_id = followers._id) WHERE user LIKE ? ORDER BY user COLLATE NOCASE", new String[] { likeFilter }); } public boolean isFollower(long userId) { Cursor cursor = mDb.query(TABLE_FOLLOWER, FOLLOWER_COLUMNS, KEY_ID + "=" + userId, null, null, null, null); boolean result = false; if (cursor != null && cursor.moveToFirst()) { result = true; } cursor.close(); return result; } public void clearData() { // TODO: just wipe the database. deleteAllTweets(TABLE_TWEET); deleteAllTweets(TABLE_MENTION); deleteAllDms(); deleteAllFollowers(); } public boolean deleteAllTweets(String tableName) { return mDb.delete(tableName, null, null) > 0; } public boolean deleteAllDms() { return mDb.delete(TABLE_DIRECTMESSAGE, null, null) > 0; } public boolean deleteAllFollowers() { return mDb.delete(TABLE_FOLLOWER, null, null) > 0; } public boolean deleteDm(String id) { return mDb.delete(TABLE_DIRECTMESSAGE, String.format("%s = '%s'", KEY_ID, id), null) > 0; } public void markAllTweetsRead(String tableName) { ContentValues values = new ContentValues(); values.put(KEY_IS_UNREAD, 0); mDb.update(tableName, values, null, null); } public void markAllDmsRead() { ContentValues values = new ContentValues(); values.put(KEY_IS_UNREAD, 0); mDb.update(TABLE_DIRECTMESSAGE, values, null, null); } public String fetchMaxId(String tableName) { Cursor mCursor = mDb.rawQuery("SELECT " + KEY_ID + " FROM " + tableName + " ORDER BY " + KEY_CREATED_AT + " DESC LIMIT 1", null); String result = null; if (mCursor == null) { return result; } mCursor.moveToFirst(); if (mCursor.getCount() == 0){ result = null; }else{ result = mCursor.getString(0); } mCursor.close(); return result; } public int fetchUnreadCount(String tableName) { Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + KEY_ID + ") FROM " + tableName + " WHERE " + KEY_IS_UNREAD + " = 1", null); int result = 0; if (mCursor == null) { return result; } mCursor.moveToFirst(); result = mCursor.getInt(0); mCursor.close(); return result; } public String fetchMaxDmId(boolean isSent) { Cursor mCursor = mDb.rawQuery("SELECT " + KEY_ID + " FROM " + TABLE_DIRECTMESSAGE + " WHERE " + KEY_IS_SENT + " = ? " + " ORDER BY " + KEY_CREATED_AT + " DESC LIMIT 1", new String[] { isSent ? "1" : "0" }); String result = null; if (mCursor == null) { return result; } mCursor.moveToFirst(); if (mCursor.getCount() == 0){ result = null; }else{ result = mCursor.getString(0); } mCursor.close(); return result; } public int addNewDmsAndCountUnread(List<Dm> dms) { addDms(dms, true); return fetchUnreadDmCount(); } public int fetchDmCount() { Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + KEY_ID + ") FROM " + TABLE_DIRECTMESSAGE, null); int result = 0; if (mCursor == null) { return result; } mCursor.moveToFirst(); result = mCursor.getInt(0); mCursor.close(); return result; } private int fetchUnreadDmCount() { Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + KEY_ID + ") FROM " + TABLE_DIRECTMESSAGE + " WHERE " + KEY_IS_UNREAD + " = 1", null); int result = 0; if (mCursor == null) { return result; } mCursor.moveToFirst(); result = mCursor.getInt(0); mCursor.close(); return result; } public void addTweets(String tableName, List<Tweet> tweets, boolean isUnread) { try { mDb.beginTransaction(); Tweet prevTweet = null; for (Tweet tweet : tweets) { if (prevTweet != null){ createTweet(tableName, prevTweet, tweet.id, isUnread); } prevTweet = tweet; } //add the last tweet with previd is empty if (prevTweet != null){ createTweet(tableName, prevTweet, "", isUnread); } //limitRows(tableName, TwitterApi.RETRIEVE_LIMIT); mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } } public Tweet getTweet(String tableName, String id){ Cursor cursor = mDb.query(tableName, TWEET_COLUMNS, KEY_ID + " = ?", new String[]{id}, null, null, null); if (cursor != null && cursor.moveToFirst()){ Tweet tweet = new Tweet(); tweet.id = cursor.getString(cursor.getColumnIndex(KEY_ID)); tweet.text = cursor.getString(cursor.getColumnIndex(KEY_TEXT)); tweet.source = cursor.getString(cursor.getColumnIndex(KEY_SOURCE)); tweet.favorited = cursor.getString(cursor.getColumnIndex(KEY_FAVORITED)); tweet.createdAt = Utils.parseDateTimeFromSqlite(cursor.getString(cursor.getColumnIndex(KEY_CREATED_AT))); tweet.profileImageUrl = cursor.getString(cursor.getColumnIndex(KEY_PROFILE_IMAGE_URL)); tweet.screenName = cursor.getString(cursor.getColumnIndex(KEY_USER)); tweet.userId = cursor.getString(cursor.getColumnIndex(KEY_USER_ID)); tweet.inReplyToScreenName = cursor.getString(cursor.getColumnIndex(KEY_IN_REPLY_TO_SCREEN_NAME)); tweet.inReplyToUserId = cursor.getString(cursor.getColumnIndex(KEY_IN_REPLY_TO_USER_ID)); tweet.inReplyToStatusId = cursor.getString(cursor.getColumnIndex(KEY_IN_REPLY_TO_STATUS_ID)); tweet.prevId = cursor.getString(cursor.getColumnIndex(KEY_PREV_ID)); cursor.close(); return tweet; }else{ return null; } } public void addTweets(List<Tweet> tweets, String id, boolean isUnread) { try { mDb.beginTransaction(); String tableName = TABLE_TWEET; Tweet prevTweet = getTweet(tableName, id); for (Tweet tweet : tweets) { if (prevTweet != null){ createTweet(tableName, prevTweet, tweet.id, isUnread); } prevTweet = tweet; } //add the last tweet with previd is empty if (prevTweet != null){ createTweet(tableName, prevTweet, null, isUnread); } //limitRows(TABLE_TWEET, TwitterApi.RETRIEVE_LIMIT); mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } } public void addDms(List<Dm> dms, boolean isUnread) { try { mDb.beginTransaction(); for (Dm dm : dms) { createDm(dm, isUnread); } //limitRows(TABLE_DIRECTMESSAGE, TwitterApi.RETRIEVE_LIMIT); mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } } //检查指定ID的消息是否存在于数据库 public boolean isTweetExists(String tableName, String id){ Cursor cursor = mDb.rawQuery("SELECT COUNT(*) " + " FROM " + tableName + " WHERE " + KEY_ID + " = ?", new String[]{id}); if (cursor != null && cursor.moveToFirst()){ int count = cursor.getInt(0); cursor.close(); if (count > 0){ Log.d(TAG, String.format("[isTweetExists], id=%s, tableName=%s, count = %d, return true", id, tableName, count)); return true; }else{ Log.d(TAG, String.format("[isTweetExists], id=%s, tableName=%s, count = %d, return false", id, tableName, count)); return false; } }else{ Log.d(TAG, "cursor=null, return false"); return false; } } //获取指定ID的消息的前一条消息的ID public String getPrevTweetID(String tableName, String id){ Cursor cursor = mDb.rawQuery("SELECT " + KEY_PREV_ID + " FROM " + tableName + " WHERE " + KEY_ID + " = ?", new String[]{id}); if (cursor != null && cursor.moveToFirst()){ String result = cursor.getString(0); cursor.close(); return result; }else{ return ""; } } //获取从指定ID开始的更早的N条消息 public List<Tweet> fetchMoreTweetsSinceId(String tableName, String id, int limit){ String prevId = getPrevTweetID(tableName, id); if(Utils.isEmpty(prevId)){ return null; }else{ int index = 0; List<Tweet> tweetList = new ArrayList<Tweet>(); do{ Tweet tweet = getTweet(tableName, prevId); prevId = tweet.prevId; tweetList.add(tweet); index++; }while(index < limit && !Utils.isEmpty(prevId)); return tweetList; } } public int limitRows(String tablename, int limit) { Cursor cursor = mDb.rawQuery("SELECT " + KEY_ID + " FROM " + tablename + " ORDER BY " + KEY_ID + " DESC LIMIT 1 OFFSET ?", new String[] { limit - 1 + "" }); int deleted = 0; if (cursor != null && cursor.moveToFirst()) { long limitId = cursor.getLong(0); deleted = mDb.delete(tablename, KEY_ID + "<" + limitId, null); } cursor.close(); return deleted; } }
Java
package com.ch_linghu.fanfoudroid.data.db; import java.util.Date; /** * All information of status table * */ public final class StatusTablesInfo { }
Java
package com.ch_linghu.fanfoudroid.data.db; import java.text.ParseException; import android.database.Cursor; import android.provider.BaseColumns; import android.util.Log; import com.ch_linghu.fanfoudroid.data.User; public final class UserInfoTable implements BaseColumns { public static final String TAG = "UserInfoTable"; public static final String TABLE_NAME = "userinfo"; public static final String FIELD_USER_NAME = "name"; public static final String FIELD_USER_SCREEN_NAME = "screen_name"; public static final String FIELD_LOCALTION = "location"; public static final String FIELD_DESCRIPTION = "description"; public static final String FIELD_PROFILE_IMAGE_URL = "profile_image_url"; public static final String FIELD_URL = "url"; public static final String FIELD_PROTECTED = "protected"; public static final String FIELD_FOLLOWERS_COUNT = "followers_count"; public static final String FIELD_FRIENDS_COUNT = "friends_count"; public static final String FIELD_FAVORITES_COUNT = "favourites_count"; public static final String FIELD_STATUSES_COUNT = "statuses_count"; public static final String FIELD_LAST_STATUS = "last_status"; public static final String FIELD_CREATED_AT = "created_at"; public static final String FIELD_FOLLOWING = "following"; public static final String FIELD_FOLLOWER_IDS="follower_ids"; public static final String[] TABLE_COLUMNS = new String[] { _ID, FIELD_USER_NAME, FIELD_USER_SCREEN_NAME, FIELD_LOCALTION, FIELD_DESCRIPTION, FIELD_PROFILE_IMAGE_URL, FIELD_URL, FIELD_PROTECTED, FIELD_FOLLOWERS_COUNT, FIELD_FRIENDS_COUNT, FIELD_FAVORITES_COUNT, FIELD_STATUSES_COUNT, FIELD_LAST_STATUS, FIELD_CREATED_AT, FIELD_FOLLOWING}; public static final String CREATE_TABLE = "create table " + TABLE_NAME + " (" + _ID + " text primary key on conflict replace, " + FIELD_USER_NAME + " text not null, " + FIELD_USER_SCREEN_NAME + " text, " + FIELD_LOCALTION + " text, " + FIELD_DESCRIPTION + " text, " + FIELD_PROFILE_IMAGE_URL + " text, " + FIELD_URL + " text, " + FIELD_PROTECTED + " boolean, " + FIELD_FOLLOWERS_COUNT + " integer, " + FIELD_FRIENDS_COUNT + " integer, " + FIELD_FAVORITES_COUNT + " integer, " + FIELD_STATUSES_COUNT + " integer, " + FIELD_LAST_STATUS + " text, " + FIELD_CREATED_AT + " date, " + FIELD_FOLLOWING + " boolean " //+FIELD_FOLLOWER_IDS+" text" + ")"; /** * TODO: 将游标解析为一条用户信息 * * @param cursor 该方法不会关闭游标 * @return 成功返回User类型的单条数据, 失败返回null */ public static User parseCursor(Cursor cursor) { if (null == cursor || 0 == cursor.getCount()) { Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty."); return null; } User user = new User(); user.id = cursor.getString(cursor.getColumnIndex(_ID)); user.name = cursor.getString(cursor.getColumnIndex(FIELD_USER_NAME)); user.screenName = cursor.getString(cursor.getColumnIndex(FIELD_USER_SCREEN_NAME)); user.location = cursor.getString(cursor.getColumnIndex(FIELD_LOCALTION)); user.description = cursor.getString(cursor.getColumnIndex(FIELD_DESCRIPTION)); user.profileImageUrl = cursor.getString(cursor.getColumnIndex(FIELD_PROFILE_IMAGE_URL)); user.url = cursor.getString(cursor.getColumnIndex(FIELD_URL)); user.isProtected = (0 == cursor.getInt(cursor.getColumnIndex(FIELD_PROTECTED))) ? false : true; user.followersCount = cursor.getInt(cursor.getColumnIndex(FIELD_FOLLOWERS_COUNT)); user.lastStatus = cursor.getString(cursor.getColumnIndex(FIELD_LAST_STATUS)); user.friendsCount = cursor.getInt(cursor.getColumnIndex(FIELD_FRIENDS_COUNT)); user.favoritesCount = cursor.getInt(cursor.getColumnIndex(FIELD_FAVORITES_COUNT)); user.statusesCount = cursor.getInt(cursor.getColumnIndex(FIELD_STATUSES_COUNT)); user.isFollowing = (0 == cursor.getInt(cursor.getColumnIndex(FIELD_FOLLOWING))) ? false : true; //TODO:报空指针异常,待查 // try { // user.createdAt = StatusDatabase.DB_DATE_FORMATTER.parse(cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_CREATED_AT))); // } catch (ParseException e) { // Log.w(TAG, "Invalid created at data."); // } return user; } }
Java
package com.ch_linghu.fanfoudroid.data.db; import java.text.ParseException; import android.database.Cursor; import android.provider.BaseColumns; import android.util.Log; import com.ch_linghu.fanfoudroid.data.Dm; /** * Table - Direct Messages * */ public final class MessageTable implements BaseColumns { public static final String TAG = "MessageTable"; public static final int TYPE_GET = 0; public static final int TYPE_SENT = 1; public static final String TABLE_NAME = "message"; public static final int MAX_ROW_NUM = 20; public static final String FIELD_USER_ID = "uid"; public static final String FIELD_USER_SCREEN_NAME = "screen_name"; public static final String FIELD_PROFILE_IMAGE_URL = "profile_image_url"; public static final String FIELD_CREATED_AT = "created_at"; public static final String FIELD_TEXT = "text"; public static final String FIELD_IN_REPLY_TO_STATUS_ID = "in_reply_to_status_id"; public static final String FIELD_IN_REPLY_TO_USER_ID = "in_reply_to_user_id"; public static final String FIELD_IN_REPLY_TO_SCREEN_NAME = "in_reply_to_screen_name"; public static final String FIELD_IS_UNREAD = "is_unread"; public static final String FIELD_IS_SENT = "is_send"; public static final String[] TABLE_COLUMNS = new String[] { _ID, FIELD_USER_SCREEN_NAME, FIELD_TEXT, FIELD_PROFILE_IMAGE_URL, FIELD_IS_UNREAD, FIELD_IS_SENT, FIELD_CREATED_AT, FIELD_USER_ID }; public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + _ID + " text primary key on conflict replace, " + FIELD_USER_SCREEN_NAME + " text not null, " + FIELD_TEXT + " text not null, " + FIELD_PROFILE_IMAGE_URL + " text not null, " + FIELD_IS_UNREAD + " boolean not null, " + FIELD_IS_SENT + " boolean not null, " + FIELD_CREATED_AT + " date not null, " + FIELD_USER_ID + " text)"; /** * TODO: 将游标解析为一条私信 * * @param cursor 该方法不会关闭游标 * @return 成功返回Dm类型的单条数据, 失败返回null */ public static Dm parseCursor(Cursor cursor) { if (null == cursor || 0 == cursor.getCount()) { Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty."); return null; } Dm dm = new Dm(); dm.id = cursor.getString(cursor.getColumnIndex(MessageTable._ID)); dm.screenName = cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_USER_SCREEN_NAME)); dm.text = cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_TEXT)); dm.profileImageUrl = cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_PROFILE_IMAGE_URL)); dm.isSent = (0 == cursor.getInt(cursor.getColumnIndex(MessageTable.FIELD_IS_SENT))) ? false : true ; try { dm.createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_CREATED_AT))); } catch (ParseException e) { Log.w(TAG, "Invalid created at data."); } dm.userId = cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_USER_ID)); return dm; } }
Java
package com.ch_linghu.fanfoudroid.data.db; import java.io.File; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.List; import java.util.Locale; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.ch_linghu.fanfoudroid.data.Dm; import com.ch_linghu.fanfoudroid.data.Tweet; /** * A Database which contains all statuses and direct-messages, use * getInstane(Context) to get a new instance * * @deprecated use TwitterDatabase */ public class StatusDatabase { private static final String TAG = "DatabaseHelper"; private static final String DATABASE_NAME = "status_db"; private static final int DATABASE_VERSION = 3; private static StatusDatabase instance = null; private DatabaseHelper mOpenHelper = null; private Context mContext = null; /** * SQLiteOpenHelper * */ private static class DatabaseHelper extends SQLiteOpenHelper { // Construct public DatabaseHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } public DatabaseHelper(Context context, String name) { this(context, name, DATABASE_VERSION); } public DatabaseHelper(Context context) { this(context, DATABASE_NAME, DATABASE_VERSION); } public DatabaseHelper(Context context, int version) { this(context, DATABASE_NAME, null, version); } public DatabaseHelper(Context context, String name, int version) { this(context, name, null, version); } @Override public void onCreate(SQLiteDatabase db) { Log.i(TAG, "Create Database."); // Log.i(TAG, StatusTable.STATUS_TABLE_CREATE); db.execSQL(StatusTable.CREATE_TABLE); db.execSQL(MessageTable.CREATE_TABLE); db.execSQL(FollowTable.CREATE_TABLE); //2011.03.01 add beta db.execSQL(UserInfoTable.CREATE_TABLE); } @Override public synchronized void close() { Log.i(TAG, "Close Database."); super.close(); } @Override public void onOpen(SQLiteDatabase db) { Log.i(TAG, "Open Database."); super.onOpen(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.i(TAG, "Upgrade Database."); dropAllTables(db); } private void dropAllTables(SQLiteDatabase db) { db.execSQL("DROP TABLE IF EXISTS " + StatusTable.TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + MessageTable.TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + FollowTable.TABLE_NAME); //2011.03.01 add db.execSQL("DROP TABLE IF EXISTS "+UserInfoTable.TABLE_NAME); } } private StatusDatabase(Context context) { mContext = context; mOpenHelper = new DatabaseHelper(context); } public static synchronized StatusDatabase getInstance(Context context) { if (null == instance) { return new StatusDatabase(context); } return instance; } // 测试用 public SQLiteOpenHelper getSQLiteOpenHelper() { return mOpenHelper; } public void close() { if (null != instance) { mOpenHelper.close(); instance = null; } } /** * 清空所有表中数据, 谨慎使用 * */ public void clearData() { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); db.execSQL("DELETE FROM " + StatusTable.TABLE_NAME); db.execSQL("DELETE FROM " + MessageTable.TABLE_NAME); db.execSQL("DELETE FROM " + FollowTable.TABLE_NAME); //2011.03.01 add db.execSQL("DELETE FROM "+UserInfoTable.TABLE_NAME); } /** * 直接删除数据库文件, 调试用 * * @return true if this file was deleted, false otherwise. * @deprecated */ private boolean deleteDatabase() { File dbFile = mContext.getDatabasePath(DATABASE_NAME); return dbFile.delete(); } /** * 取出某类型的一条消息 * * @param tweetId * @param type of status * <li>StatusTable.TYPE_HOME</li> * <li>StatusTable.TYPE_MENTION</li> * <li>StatusTable.TYPE_USER</li> * <li>StatusTable.TYPE_FAVORITE</li> * <li>-1 means all types</li> * @return 将Cursor转换过的Tweet对象 */ public Tweet queryTweet(String tweetId, int type) { SQLiteDatabase Db = mOpenHelper.getWritableDatabase(); String selection = StatusTable._ID + "=? "; if (-1 != type) { selection += " AND " + StatusTable.FIELD_STATUS_TYPE + "=" + type; } Cursor cursor = Db.query(StatusTable.TABLE_NAME, StatusTable.TABLE_COLUMNS, selection, new String[] { tweetId }, null, null, null); Tweet tweet = null; if (cursor != null) { cursor.moveToFirst(); if (cursor.getCount() > 0) { tweet = StatusTable.parseCursor(cursor); } } cursor.close(); return tweet; } /** * 快速检查某条消息是否存在(指定类型) * * @param tweetId * @param type * <li>StatusTable.TYPE_HOME</li> * <li>StatusTable.TYPE_MENTION</li> * <li>StatusTable.TYPE_USER</li> * <li>StatusTable.TYPE_FAVORITE</li> * @return is exists */ public boolean isExists(String tweetId, int type) { SQLiteDatabase Db = mOpenHelper.getWritableDatabase(); boolean result = false; Cursor cursor = Db.query(StatusTable.TABLE_NAME, new String[] { StatusTable._ID }, StatusTable._ID + " =? AND " + StatusTable.FIELD_STATUS_TYPE + " = " + type, new String[] { tweetId }, null, null, null); if (cursor != null && cursor.getCount() > 0) { result = true; } cursor.close(); return result; } /** * 删除一条消息 * * @param tweetId * @param type -1 means all types * @return the number of rows affected if a whereClause is passed in, 0 * otherwise. To remove all rows and get a count pass "1" as the * whereClause. */ public int deleteTweet(String tweetId, int type) { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); String where = StatusTable._ID + " =? "; if (-1 != type) { where += " AND " + StatusTable.FIELD_STATUS_TYPE + " = " + type; } return db.delete(StatusTable.TABLE_NAME, where, new String[] { tweetId }); } /** * 删除超过MAX_ROW_NUM垃圾数据 * * @param type * <li>StatusTable.TYPE_HOME</li> * <li>StatusTable.TYPE_MENTION</li> * <li>StatusTable.TYPE_USER</li> * <li>StatusTable.TYPE_FAVORITE</li> * <li>-1 means all types</li> */ public void gc(int type) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); String sql = "DELETE FROM " + StatusTable.TABLE_NAME + " WHERE " + StatusTable._ID + " NOT IN " + " (SELECT " + StatusTable._ID // 子句 + " FROM " + StatusTable.TABLE_NAME; if (type != -1){ sql += " WHERE " + StatusTable.FIELD_STATUS_TYPE + " = " + type + " "; } sql += " ORDER BY " + StatusTable.FIELD_CREATED_AT + " DESC LIMIT " + StatusTable.MAX_ROW_NUM + ")"; if (type != -1) { sql += " AND " + StatusTable.FIELD_STATUS_TYPE + " = " + type + " "; } Log.d(TAG, sql); mDb.execSQL(sql); } public final static DateFormat DB_DATE_FORMATTER = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US); /** * 向Status表中写入一行数据, 此方法为私有方法, 外部插入数据请使用 putTweets() * * @param tweet * 需要写入的单条消息 * @return the row ID of the newly inserted row, or -1 if an error occurred */ public long insertTweet(Tweet tweet, int type, boolean isUnread) { SQLiteDatabase Db = mOpenHelper.getWritableDatabase(); if (isExists(tweet.id, type)) { Log.i(TAG, tweet.id + "is exists."); return -1; } ContentValues initialValues = makeTweetValues(tweet, type, isUnread); long id = Db.insert(StatusTable.TABLE_NAME, null, initialValues); if (-1 == id) { Log.e(TAG, "cann't insert the tweet : " + tweet.toString()); } else { Log.i(TAG, "Insert a status into datebase : " + tweet.toString()); } return id; } /** * 更新一条消息 * * @param tweetId * @param values * ContentValues 需要更新字段的键值对 * @return the number of rows affected */ public int updateTweet(String tweetId, ContentValues values) { Log.i(TAG, "Update Tweet : " + tweetId + " " + values.toString()); SQLiteDatabase Db = mOpenHelper.getWritableDatabase(); return Db.update(StatusTable.TABLE_NAME, values, StatusTable._ID + "=?", new String[] { tweetId }); } private ContentValues makeTweetValues(Tweet tweet, int type, boolean isUnread) { // 插入一条新消息 ContentValues initialValues = new ContentValues(); initialValues.put(StatusTable.FIELD_STATUS_TYPE, type); initialValues.put(StatusTable._ID, tweet.id); initialValues.put(StatusTable.FIELD_TEXT, tweet.text); initialValues.put(StatusTable.FIELD_USER_ID, tweet.userId); initialValues.put(StatusTable.FIELD_USER_SCREEN_NAME, tweet.screenName); initialValues.put(StatusTable.FIELD_PROFILE_IMAGE_URL, tweet.profileImageUrl); initialValues.put(StatusTable.FIELD_FAVORITED, tweet.favorited); initialValues.put(StatusTable.FIELD_IN_REPLY_TO_STATUS_ID, tweet.inReplyToStatusId); initialValues.put(StatusTable.FIELD_IN_REPLY_TO_USER_ID, tweet.inReplyToUserId); initialValues.put(StatusTable.FIELD_IN_REPLY_TO_SCREEN_NAME, tweet.inReplyToScreenName); // initialValues.put(FIELD_IS_REPLY, tweet.isReply()); initialValues.put(StatusTable.FIELD_CREATED_AT, DB_DATE_FORMATTER.format(tweet.createdAt)); initialValues.put(StatusTable.FIELD_SOURCE, tweet.source); initialValues.put(StatusTable.FIELD_PIC_THUMB, tweet.thumbnail_pic); initialValues.put(StatusTable.FIELD_PIC_MID, tweet.bmiddle_pic); initialValues.put(StatusTable.FIELD_PIC_ORIG, tweet.original_pic); initialValues.put(StatusTable.FIELD_IS_UNREAD, isUnread); initialValues.put(StatusTable.FIELD_TRUNCATED, tweet.truncated); // TODO: truncated return initialValues; } /** * 写入N条消息 * * @param tweets * 需要写入的消息List * @return */ public void putTweets(List<Tweet> tweets, int type, boolean isUnread) { //long start = System.currentTimeMillis(); if (null == tweets || 0 == tweets.size()) return; SQLiteDatabase db = mOpenHelper.getWritableDatabase(); try { db.beginTransaction(); for (int i = tweets.size() - 1; i >= 0; i--) { Tweet tweet = tweets.get(i); ContentValues initialValues = makeTweetValues(tweet, type, isUnread); long id = db.insert(StatusTable.TABLE_NAME, null, initialValues); if (-1 == id) { Log.e(TAG, "cann't insert the tweet : " + tweet.toString()); } else { Log.i(TAG, "Insert a status into datebase : " + tweet.toString()); } } // gc(type); // 保持总量 db.setTransactionSuccessful(); } finally { db.endTransaction(); } //long end = System.currentTimeMillis(); //Log.d("LDS", "putTweets : " + (end-start)); } /** * 取出某一类型的所有消息 * * @param tableName * @return a cursor */ public Cursor fetchAllTweets(int type) { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); return mDb.query(StatusTable.TABLE_NAME, StatusTable.TABLE_COLUMNS, StatusTable.FIELD_STATUS_TYPE + " = " + type, null, null, null, StatusTable.FIELD_CREATED_AT + " DESC "); //LIMIT " + StatusTable.MAX_ROW_NUM); } /** * 清空某类型的所有信息 * * @param tableName * @return the number of rows affected if a whereClause is passed in, 0 * otherwise. To remove all rows and get a count pass "1" as the * whereClause. */ public int dropAllTweets(int type) { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); return mDb.delete(StatusTable.TABLE_NAME, StatusTable.FIELD_STATUS_TYPE + " = " + type, null); } /** * 取出本地某类型最新消息ID * * @param type * @return The newest Status Id */ public String fetchMaxTweetId(int type) { return fetchMaxOrMinTweetId(type, true); } /** * 取出本地某类型最旧消息ID * * @param tableName * @return The oldest Status Id */ public String fetchMinTweetId(int type) { return fetchMaxOrMinTweetId(type, false); } private String fetchMaxOrMinTweetId(int type, boolean isMax) { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); String sql = "SELECT " + StatusTable._ID + " FROM " + StatusTable.TABLE_NAME + " WHERE " + StatusTable.FIELD_STATUS_TYPE + "=" + type + " ORDER BY " + StatusTable.FIELD_CREATED_AT; if (isMax) sql += " DESC "; Cursor mCursor = mDb.rawQuery(sql + " LIMIT 1", null); String result = null; if (mCursor == null) { return result; } mCursor.moveToFirst(); if (mCursor.getCount() == 0) { result = null; } else { result = mCursor.getString(0); } mCursor.close(); return result; } /** * Count unread tweet * * @param tableName * @return */ public int fetchUnreadCount(int type) { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + StatusTable._ID + ")" + " FROM " + StatusTable.TABLE_NAME + " WHERE " + StatusTable.FIELD_STATUS_TYPE + " = " + type + " AND " + StatusTable.FIELD_IS_UNREAD + " = 1 ", // "LIMIT " + StatusTable.MAX_ROW_NUM, null); int result = 0; if (mCursor == null) { return result; } mCursor.moveToFirst(); result = mCursor.getInt(0); mCursor.close(); return result; } public int addNewTweetsAndCountUnread(List<Tweet> tweets, int type) { putTweets(tweets, type, true); return fetchUnreadCount(type); } /** * Set isFavorited * * @param tweetId * @param isFavorited * @return Is Succeed */ public boolean setFavorited(String tweetId, String isFavorited) { ContentValues values = new ContentValues(); values.put(StatusTable.FIELD_FAVORITED, isFavorited); int i = updateTweet(tweetId, values); return (i > 0) ? true : false; } // DM & Follower /** * 写入一条私信 * * @param dm * @param isUnread * @return the row ID of the newly inserted row, or -1 if an error occurred, * 因为主键的原因,此处返回的不是 _ID 的值, 而是一个自增长的 row_id */ public long createDm(Dm dm, boolean isUnread) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); ContentValues initialValues = new ContentValues(); initialValues.put(MessageTable._ID, dm.id); initialValues.put(MessageTable.FIELD_USER_SCREEN_NAME, dm.screenName); initialValues.put(MessageTable.FIELD_TEXT, dm.text); initialValues.put(MessageTable.FIELD_PROFILE_IMAGE_URL, dm.profileImageUrl); initialValues.put(MessageTable.FIELD_IS_UNREAD, isUnread); initialValues.put(MessageTable.FIELD_IS_SENT, dm.isSent); initialValues.put(MessageTable.FIELD_CREATED_AT, DB_DATE_FORMATTER.format(dm.createdAt)); initialValues.put(MessageTable.FIELD_USER_ID, dm.userId); return mDb.insert(MessageTable.TABLE_NAME, null, initialValues); } // /** * Create a follower * * @param userId * @return the row ID of the newly inserted row, or -1 if an error occurred */ public long createFollower(String userId) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); ContentValues initialValues = new ContentValues(); initialValues.put(FollowTable._ID, userId); long rowId = mDb.insert(FollowTable.TABLE_NAME, null, initialValues); if (-1 == rowId) { Log.e(TAG, "Cann't create Follower : " + userId); } else { Log.i(TAG, "create create follower : " + userId); } return rowId; } /** * 清空Followers表并添加新内容 * * @param followers */ public void syncFollowers(List<String> followers) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); try { mDb.beginTransaction(); deleteAllFollowers(); for (String userId : followers) { createFollower(userId); } mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } } /** * @param type * <li>MessageTable.TYPE_SENT</li> * <li>MessageTable.TYPE_GET</li> * <li>其他任何值都认为取出所有类型</li> * @return */ public Cursor fetchAllDms(int type) { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); String selection = null; if (MessageTable.TYPE_SENT == type) { selection = MessageTable.FIELD_IS_SENT + " = " + MessageTable.TYPE_SENT; } else if (MessageTable.TYPE_GET == type) { selection = MessageTable.FIELD_IS_SENT + " = " + MessageTable.TYPE_GET; } return mDb.query(MessageTable.TABLE_NAME, MessageTable.TABLE_COLUMNS, selection, null, null, null, MessageTable.FIELD_CREATED_AT + " DESC"); } public Cursor fetchInboxDms() { return fetchAllDms(MessageTable.TYPE_GET); } public Cursor fetchSendboxDms() { return fetchAllDms(MessageTable.TYPE_SENT); } public Cursor fetchAllFollowers() { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); return mDb.query(FollowTable.TABLE_NAME, FollowTable.TABLE_COLUMNS, null, null, null, null, null); } /** * FIXME: * @param filter * @return */ public Cursor getFollowerUsernames(String filter) { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); String likeFilter = '%' + filter + '%'; // FIXME: 此方法的作用应该是在于在写私信时自动完成联系人的功能, // 改造数据库后,因为本地tweets表中的数据有限, 所以几乎使得该功能没有实际价值(因为能从数据库中读到的联系人很少) // 在完成关注者/被关注者两个界面后, 看能不能使得本地有一份 // [互相关注] 的 id/name 缓存(即getFriendsIds和getFollowersIds的交集, 因为客户端只能给他们发私信, 如果按现在 // 只提示followers的列表则很容易造成服务器返回"只能给互相关注的人发私信"的错误信息, 这会造成用户无法理解, 因为此联系人是我们提供给他们选择的, // 并且将目前的自动完成功能的基础上加一个[选择联系人]按钮, 用于启动一个新的联系人列表页面以显示所有可发送私信的联系人对象, 类似手机写短信时的选择联系人功能 return null; // FIXME: clean this up. 新数据库中失效, 表名, 列名 // return mDb.rawQuery( // "SELECT user_id AS _id, user" // + " FROM (SELECT user_id, user FROM tweets" // + " INNER JOIN followers on tweets.user_id = followers._id UNION" // + " SELECT user_id, user FROM dms INNER JOIN followers" // + " on dms.user_id = followers._id)" // + " WHERE user LIKE ?" // + " ORDER BY user COLLATE NOCASE", // new String[] { likeFilter }); } /** * @param userId * 该用户是否follow Me * @deprecated 未使用 * @return */ public boolean isFollower(String userId) { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); Cursor cursor = mDb.query(FollowTable.TABLE_NAME, FollowTable.TABLE_COLUMNS, FollowTable._ID + "= ?", new String[] { userId }, null, null, null); boolean result = false; if (cursor != null && cursor.moveToFirst()) { result = true; } cursor.close(); return result; } public boolean deleteAllFollowers() { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); return mDb.delete(FollowTable.TABLE_NAME, null, null) > 0; } public boolean deleteDm(String id) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); return mDb.delete(MessageTable.TABLE_NAME, String.format("%s = '%s'", MessageTable._ID, id), null) > 0; } /** * @param tableName * @return the number of rows affected */ public int markAllTweetsRead(int type) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(StatusTable.FIELD_IS_UNREAD, 0); return mDb.update(StatusTable.TABLE_NAME, values, StatusTable.FIELD_STATUS_TYPE + "=" + type, null); } public boolean deleteAllDms() { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); return mDb.delete(MessageTable.TABLE_NAME, null, null) > 0; } public int markAllDmsRead() { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(MessageTable.FIELD_IS_UNREAD, 0); return mDb.update(MessageTable.TABLE_NAME, values, null, null); } public String fetchMaxDmId(boolean isSent) { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); Cursor mCursor = mDb.rawQuery("SELECT " + MessageTable._ID + " FROM " + MessageTable.TABLE_NAME + " WHERE " + MessageTable.FIELD_IS_SENT + " = ? " + " ORDER BY " + MessageTable.FIELD_CREATED_AT + " DESC LIMIT 1", new String[] { isSent ? "1" : "0" }); String result = null; if (mCursor == null) { return result; } mCursor.moveToFirst(); if (mCursor.getCount() == 0) { result = null; } else { result = mCursor.getString(0); } mCursor.close(); return result; } public int addNewDmsAndCountUnread(List<Dm> dms) { addDms(dms, true); return fetchUnreadDmCount(); } public int fetchDmCount() { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + MessageTable._ID + ") FROM " + MessageTable.TABLE_NAME, null); int result = 0; if (mCursor == null) { return result; } mCursor.moveToFirst(); result = mCursor.getInt(0); mCursor.close(); return result; } private int fetchUnreadDmCount() { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + MessageTable._ID + ") FROM " + MessageTable.TABLE_NAME + " WHERE " + MessageTable.FIELD_IS_UNREAD + " = 1", null); int result = 0; if (mCursor == null) { return result; } mCursor.moveToFirst(); result = mCursor.getInt(0); mCursor.close(); return result; } public void addDms(List<Dm> dms, boolean isUnread) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); try { mDb.beginTransaction(); for (Dm dm : dms) { createDm(dm, isUnread); } // limitRows(TABLE_DIRECTMESSAGE, TwitterApi.RETRIEVE_LIMIT); mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } } //2011.03.01 add //UserInfo操作 public Cursor getAllUserInfo(){ SQLiteDatabase mDb=mOpenHelper.getReadableDatabase(); return mDb.query(UserInfoTable.TABLE_NAME,UserInfoTable.TABLE_COLUMNS, null, null, null, null, null); } /** * 根据id列表获取user数据 * @param userIds * @return */ public Cursor getUserInfoByIds(String[] userIds){ SQLiteDatabase mDb=mOpenHelper.getReadableDatabase(); String userIdStr=""; for(String id:userIds){ userIdStr+="'"+id+"',"; } userIdStr=userIdStr.substring(0, userIdStr.lastIndexOf(","));//删除最后的逗号 return mDb.query(UserInfoTable.TABLE_NAME, UserInfoTable.TABLE_COLUMNS, UserInfoTable._ID+" in ("+userIdStr+")", null, null, null, null); } /** * 新建用户 * * @param user * @return the row ID of the newly inserted row, or -1 if an error occurred */ public long createUserInfo(com.ch_linghu.fanfoudroid.data.User user) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); ContentValues initialValues = new ContentValues(); initialValues.put(UserInfoTable._ID, user.id); initialValues.put(UserInfoTable.FIELD_USER_NAME, user.name); initialValues.put(UserInfoTable.FIELD_USER_SCREEN_NAME, user.screenName); initialValues.put(UserInfoTable.FIELD_LOCALTION, user.location); initialValues.put(UserInfoTable.FIELD_DESCRIPTION, user.description); initialValues.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, user.profileImageUrl); initialValues.put(UserInfoTable.FIELD_URL, user.url); initialValues.put(UserInfoTable.FIELD_PROTECTED, user.isProtected); initialValues.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, user.followersCount); initialValues.put(UserInfoTable.FIELD_LAST_STATUS, user.lastStatus); initialValues.put(UserInfoTable.FIELD_FRIENDS_COUNT, user.friendsCount); initialValues.put(UserInfoTable.FIELD_FAVORITES_COUNT, user.favoritesCount); initialValues.put(UserInfoTable.FIELD_STATUSES_COUNT, user.statusesCount); initialValues.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing); long rowId = mDb.insert(UserInfoTable.TABLE_NAME, null, initialValues); if (-1 == rowId) { Log.e(TAG, "Cann't create Follower : " + user.id); } else { Log.i(TAG, "create create follower : " + user.id); } return rowId; } /** * 新建用户重载,防止转换引起的性能损失() * @param user * @return */ public long createWeiboUserInfo(com.ch_linghu.fanfoudroid.weibo.User user){ SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); ContentValues args = new ContentValues(); args.put(UserInfoTable._ID, user.getName()); args.put(UserInfoTable.FIELD_USER_NAME, user.getName()); args.put(UserInfoTable.FIELD_USER_SCREEN_NAME, user.getScreenName()); String location = user.getLocation(); args.put(UserInfoTable.FIELD_LOCALTION, location); String description = user.getDescription(); args.put(UserInfoTable.FIELD_DESCRIPTION, description); args.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, user.getProfileBackgroundImageUrl()); if (user.getURL() != null) { args.put(UserInfoTable.FIELD_URL, user.getURL().toString()); } args.put(UserInfoTable.FIELD_PROTECTED, user.isProtected()); args.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, user.getFollowersCount()); args.put(UserInfoTable.FIELD_LAST_STATUS, user.getStatusSource()); args.put(UserInfoTable.FIELD_FRIENDS_COUNT, user.getFriendsCount()); args.put(UserInfoTable.FIELD_FAVORITES_COUNT, user.getFavouritesCount()); args.put(UserInfoTable.FIELD_STATUSES_COUNT, user.getStatusesCount()); args.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing()); long rowId = mDb.insert(UserInfoTable.TABLE_NAME, null, args); if (-1 == rowId) { Log.e(TAG, "Cann't create Follower : " + user.getId()); } else { Log.i(TAG, "create create follower : " + user.getId()); } return rowId; } /** * 查看数据是否已保存用户数据 * @param userId * @return */ public boolean existsUser(String userId) { SQLiteDatabase Db = mOpenHelper.getReadableDatabase(); boolean result = false; Cursor cursor = Db.query(UserInfoTable.TABLE_NAME, new String[] { UserInfoTable._ID }, UserInfoTable._ID +"='"+userId+"'", null, null, null, null); Log.i("testesetesteste", String.valueOf(cursor.getCount())); if (cursor != null && cursor.getCount() > 0) { result = true; } cursor.close(); return result; } /** * 根据userid提取信息 * @param userId * @return */ public Cursor getUserInfoById(String userId){ SQLiteDatabase Db = mOpenHelper.getReadableDatabase(); Cursor cursor = Db.query(UserInfoTable.TABLE_NAME, UserInfoTable.TABLE_COLUMNS, UserInfoTable._ID + " = '" +userId+"'", null, null, null, null); return cursor; } /** * 更新用户 * @param uid * @param args * @return */ public boolean updateUser(String uid,ContentValues args){ SQLiteDatabase Db=mOpenHelper.getWritableDatabase(); return Db.update(UserInfoTable.TABLE_NAME, args, UserInfoTable._ID+"='"+uid+"'", null)>0; } /** * 更新用户信息 */ public boolean updateUser(com.ch_linghu.fanfoudroid.data.User user){ SQLiteDatabase Db=mOpenHelper.getWritableDatabase(); ContentValues args=new ContentValues(); args.put(UserInfoTable._ID, user.id); args.put(UserInfoTable.FIELD_USER_NAME, user.name); args.put(UserInfoTable.FIELD_USER_SCREEN_NAME, user.screenName); args.put(UserInfoTable.FIELD_LOCALTION, user.location); args.put(UserInfoTable.FIELD_DESCRIPTION, user.description); args.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, user.profileImageUrl); args.put(UserInfoTable.FIELD_URL, user.url); args.put(UserInfoTable.FIELD_PROTECTED, user.isProtected); args.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, user.followersCount); args.put(UserInfoTable.FIELD_LAST_STATUS, user.lastStatus); args.put(UserInfoTable.FIELD_FRIENDS_COUNT, user.friendsCount); args.put(UserInfoTable.FIELD_FAVORITES_COUNT, user.favoritesCount); args.put(UserInfoTable.FIELD_STATUSES_COUNT, user.statusesCount); args.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing); return Db.update(UserInfoTable.TABLE_NAME, args, UserInfoTable._ID+"='"+user.id+"'", null)>0; } /** * 减少转换的开销 * @param user * @return */ public boolean updateWeiboUser(com.ch_linghu.fanfoudroid.weibo.User user){ SQLiteDatabase Db=mOpenHelper.getWritableDatabase(); ContentValues args = new ContentValues(); args.put(UserInfoTable._ID, user.getName()); args.put(UserInfoTable.FIELD_USER_NAME, user.getName()); args.put(UserInfoTable.FIELD_USER_SCREEN_NAME, user.getScreenName()); String location = user.getLocation(); args.put(UserInfoTable.FIELD_LOCALTION, location); String description = user.getDescription(); args.put(UserInfoTable.FIELD_DESCRIPTION, description); args.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, user.getProfileBackgroundImageUrl()); if (user.getURL() != null) { args.put(UserInfoTable.FIELD_URL, user.getURL().toString()); } args.put(UserInfoTable.FIELD_PROTECTED, user.isProtected()); args.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, user.getFollowersCount()); args.put(UserInfoTable.FIELD_LAST_STATUS, user.getStatusSource()); args.put(UserInfoTable.FIELD_FRIENDS_COUNT, user.getFriendsCount()); args.put(UserInfoTable.FIELD_FAVORITES_COUNT, user.getFavouritesCount()); args.put(UserInfoTable.FIELD_STATUSES_COUNT, user.getStatusesCount()); args.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing()); return Db.update(UserInfoTable.TABLE_NAME, args, UserInfoTable._ID+"='"+user.getId()+"'", null)>0; } /** * 同步用户,更新已存在的用户,插入未存在的用户 */ public void syncUsers(List<com.ch_linghu.fanfoudroid.data.User> users){ SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); try{ mDb.beginTransaction(); for(com.ch_linghu.fanfoudroid.data.User u:users){ if(existsUser(u.id)){ updateUser(u); }else{ createUserInfo(u); } } mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } } public void syncWeiboUsers(List<com.ch_linghu.fanfoudroid.weibo.User> users){ SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); try{ mDb.beginTransaction(); for(com.ch_linghu.fanfoudroid.weibo.User u:users){ if(existsUser(u.getId())){ updateWeiboUser(u); }else{ createWeiboUserInfo(u); } } mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } } }
Java
package com.ch_linghu.fanfoudroid.data.db; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.provider.BaseColumns; import android.util.Log; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.helper.Utils; /** * Table - Statuses * <br /> <br /> * 为节省流量,故此表不保证本地数据库中所有消息具有前后连贯性, 而只确保最新的MAX_ROW_NUM条<br /> * 数据的连贯性, 超出部分则视为垃圾数据, 不再允许读取, 也不保证其是前后连续的.<br /> * <br /> * 因为用户可能中途长时间停止使用本客户端,而换其他客户端(如网页), <br /> * 如果保证本地所有数据的连贯性, 那么就必须自动去下载所有本地缺失的中间数据,<br /> * 而这些数据极有可能是用户通过其他客户端阅读过的无用信息, 浪费了用户流量.<br /> * <br /> * 即认为相对于旧信息而言, 新信息对于用户更为价值, 所以只会新信息进行维护, <br /> * 而旧信息一律视为无用的, 如用户需要查看超过MAX_ROW_NUM的旧数据, 可主动点击, <br /> * 从而请求服务器. 本地只缓存最有价值的MAX条最新信息.<br /> * <br /> * 本地数据库中前MAX_ROW_NUM条的数据模拟一个定长列队, 即在尾部插入N条消息, 就会使得头部<br /> * 的N条消息被标记为垃圾数据(但并不立即收回),只有在认为数据库数据过多时,<br /> * 可手动调用 <code>StatusDatabase.gc(int type)</code> 方法进行垃圾清理.<br /> * * */ public final class StatusTable implements BaseColumns { public static final String TAG = "StatusTable"; // Status Types public static final int TYPE_HOME = 1; //首页(我和我的好友) public static final int TYPE_MENTION = 2; //提到我的 public static final int TYPE_USER = 3; //指定USER的 public static final int TYPE_FAVORITE = 4; //收藏 public static final int TYPE_BROWSE = 5; //随便看看 public static final String TABLE_NAME = "status"; public static final int MAX_ROW_NUM = 20; //单类型数据安全区域 public static final String FIELD_OWNER_ID = "owner"; //用于标识数据的所有者。以便于处理其他用户的信息(如其他用户的收藏) public static final String FIELD_USER_ID = "uid"; public static final String FIELD_USER_SCREEN_NAME = "screen_name"; public static final String FIELD_PROFILE_IMAGE_URL = "profile_image_url"; public static final String FIELD_CREATED_AT = "created_at"; public static final String FIELD_TEXT = "text"; public static final String FIELD_SOURCE = "source"; public static final String FIELD_TRUNCATED = "truncated"; public static final String FIELD_IN_REPLY_TO_STATUS_ID = "in_reply_to_status_id"; public static final String FIELD_IN_REPLY_TO_USER_ID = "in_reply_to_user_id"; public static final String FIELD_IN_REPLY_TO_SCREEN_NAME = "in_reply_to_screen_name"; public static final String FIELD_FAVORITED = "favorited"; public static final String FIELD_IS_UNREAD = "is_unread"; public static final String FIELD_STATUS_TYPE = "status_type"; public static final String FIELD_PIC_THUMB = "pic_thumbnail"; public static final String FIELD_PIC_MID = "pic_middle"; public static final String FIELD_PIC_ORIG = "pic_original"; // private static final String FIELD_PHOTO_URL = "photo_url"; // private double latitude = -1; // private double longitude = -1; // private String thumbnail_pic; // private String bmiddle_pic; // private String original_pic; public static final String[] TABLE_COLUMNS = new String[] {_ID, FIELD_USER_SCREEN_NAME, FIELD_TEXT, FIELD_PROFILE_IMAGE_URL, FIELD_IS_UNREAD, FIELD_CREATED_AT, FIELD_FAVORITED, FIELD_IN_REPLY_TO_STATUS_ID, FIELD_IN_REPLY_TO_USER_ID, FIELD_IN_REPLY_TO_SCREEN_NAME, FIELD_TRUNCATED, FIELD_PIC_THUMB, FIELD_PIC_MID, FIELD_PIC_ORIG, FIELD_SOURCE, FIELD_USER_ID, FIELD_STATUS_TYPE, FIELD_OWNER_ID}; public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + _ID + " text not null," + FIELD_STATUS_TYPE + " text not null, " + FIELD_OWNER_ID + " text not null, " + FIELD_USER_ID + " text not null, " + FIELD_USER_SCREEN_NAME + " text not null, " + FIELD_TEXT + " text not null, " + FIELD_PROFILE_IMAGE_URL + " text not null, " + FIELD_IS_UNREAD + " boolean not null, " + FIELD_CREATED_AT + " date not null, " + FIELD_FAVORITED + " text, " + FIELD_IN_REPLY_TO_STATUS_ID + " text, " + FIELD_IN_REPLY_TO_USER_ID + " text, " + FIELD_IN_REPLY_TO_SCREEN_NAME + " text, " + FIELD_PIC_THUMB + " text, " + FIELD_PIC_MID + " text, " + FIELD_PIC_ORIG + " text, " + FIELD_SOURCE + " text not null, " + FIELD_TRUNCATED + " boolean ," + "PRIMARY KEY (" + _ID + ","+ FIELD_OWNER_ID + "," + FIELD_STATUS_TYPE + "))"; /** * 将游标解析为一条Tweet * * * @param cursor 该方法不会移动或关闭游标 * @return 成功返回 Tweet 类型的单条数据, 失败返回null */ public static Tweet parseCursor(Cursor cursor) { if (null == cursor || 0 == cursor.getCount()) { Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty."); return null; } else if ( -1 == cursor.getPosition() ) { cursor.moveToFirst(); } Tweet tweet = new Tweet(); tweet.id = cursor.getString(cursor.getColumnIndex(_ID)); tweet.createdAt = Utils.parseDateTimeFromSqlite(cursor.getString(cursor.getColumnIndex(FIELD_CREATED_AT))); tweet.favorited = cursor.getString(cursor.getColumnIndex(FIELD_FAVORITED)); tweet.screenName = cursor.getString(cursor.getColumnIndex(FIELD_USER_SCREEN_NAME)); tweet.userId = cursor.getString(cursor.getColumnIndex(FIELD_USER_ID)); tweet.text = cursor.getString(cursor.getColumnIndex(FIELD_TEXT)); tweet.source = cursor.getString(cursor.getColumnIndex(FIELD_SOURCE)); tweet.profileImageUrl = cursor.getString(cursor.getColumnIndex(FIELD_PROFILE_IMAGE_URL)); tweet.inReplyToScreenName = cursor.getString(cursor.getColumnIndex(FIELD_IN_REPLY_TO_SCREEN_NAME)); tweet.inReplyToStatusId = cursor.getString(cursor.getColumnIndex(FIELD_IN_REPLY_TO_STATUS_ID)); tweet.inReplyToUserId = cursor.getString(cursor.getColumnIndex(FIELD_IN_REPLY_TO_USER_ID)); tweet.truncated = cursor.getString(cursor.getColumnIndex(FIELD_TRUNCATED)); tweet.thumbnail_pic = cursor.getString(cursor.getColumnIndex(FIELD_PIC_THUMB)); tweet.bmiddle_pic = cursor.getString(cursor.getColumnIndex(FIELD_PIC_MID)); tweet.original_pic = cursor.getString(cursor.getColumnIndex(FIELD_PIC_ORIG)); tweet.setStatusType(cursor.getInt(cursor.getColumnIndex(FIELD_STATUS_TYPE)) ); return tweet; } }
Java
package com.ch_linghu.fanfoudroid.data.db; import java.text.ParseException; import android.database.Cursor; import android.provider.BaseColumns; import android.util.Log; import com.ch_linghu.fanfoudroid.data.User; /** * Table - Followers * */ public final class FollowTable implements BaseColumns { public static final String TAG = "FollowTable"; public static final String TABLE_NAME = "followers"; public static final String FIELD_USER_NAME = "name"; public static final String FIELD_USER_SCREEN_NAME = "screen_name"; public static final String FIELD_LOCALTION = "location"; public static final String FIELD_DESCRIPTION = "description"; public static final String FIELD_PROFILE_IMAGE_URL = "profile_image_url"; public static final String FIELD_URL = "url"; public static final String FIELD_PROTECTED = "protected"; public static final String FIELD_FOLLOWERS_COUNT = "followers_count"; public static final String FIELD_FRIENDS_COUNT = "friends_count"; public static final String FIELD_FAVORITES_COUNT = "favourites_count"; public static final String FIELD_STATUSES_COUNT = "statuses_count"; public static final String FIELD_LAST_STATUS = "last_status"; public static final String FIELD_CREATED_AT = "created_at"; public static final String FIELD_FOLLOWING = "following"; public static final String[] TABLE_COLUMNS = new String[] { _ID, FIELD_USER_NAME, FIELD_USER_SCREEN_NAME, FIELD_LOCALTION, FIELD_DESCRIPTION, FIELD_PROFILE_IMAGE_URL, FIELD_URL, FIELD_PROTECTED, FIELD_FOLLOWERS_COUNT, FIELD_FRIENDS_COUNT, FIELD_FAVORITES_COUNT, FIELD_STATUSES_COUNT, FIELD_LAST_STATUS, FIELD_CREATED_AT, FIELD_FOLLOWING}; public static final String CREATE_TABLE = "create table " + TABLE_NAME + " (" + _ID + " text primary key on conflict replace, " + FIELD_USER_NAME + " text not null, " + FIELD_USER_SCREEN_NAME + " text, " + FIELD_LOCALTION + " text, " + FIELD_DESCRIPTION + " text, " + FIELD_PROFILE_IMAGE_URL + " text, " + FIELD_URL + " text, " + FIELD_PROTECTED + " boolean, " + FIELD_FOLLOWERS_COUNT + " integer, " + FIELD_FRIENDS_COUNT + " integer, " + FIELD_FAVORITES_COUNT + " integer, " + FIELD_STATUSES_COUNT + " integer, " + FIELD_LAST_STATUS + " text, " + FIELD_CREATED_AT + " date, " + FIELD_FOLLOWING + " boolean " + ")"; /** * TODO: 将游标解析为一条用户信息 * * @param cursor 该方法不会关闭游标 * @return 成功返回User类型的单条数据, 失败返回null */ public static User parseCursor(Cursor cursor) { if (null == cursor || 0 == cursor.getCount()) { Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty."); return null; } User user = new User(); user.id = cursor.getString(cursor.getColumnIndex(FollowTable._ID)); user.name = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_USER_NAME)); user.screenName = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_USER_SCREEN_NAME)); user.location = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_LOCALTION)); user.description = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_DESCRIPTION)); user.profileImageUrl = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_PROFILE_IMAGE_URL)); user.url = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_URL)); user.isProtected = (0 == cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_PROTECTED))) ? false : true; user.followersCount = cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_FOLLOWERS_COUNT)); user.lastStatus = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_LAST_STATUS));; user.friendsCount = cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_FRIENDS_COUNT)); user.favoritesCount = cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_FAVORITES_COUNT)); user.statusesCount = cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_STATUSES_COUNT)); user.isFollowing = (0 == cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_FOLLOWING))) ? false : true; try { user.createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_CREATED_AT))); } catch (ParseException e) { Log.w(TAG, "Invalid created at data."); } return user; } }
Java
package com.ch_linghu.fanfoudroid.data.db; import java.io.File; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.List; import java.util.Locale; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.data.Dm; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.helper.Preferences; import com.ch_linghu.fanfoudroid.helper.Utils; /** * A Database which contains all statuses and direct-messages, use * getInstane(Context) to get a new instance * */ public class TwitterDatabase { private static final String TAG = "DatabaseHelper"; private static final String DATABASE_NAME = "status_db"; private static final int DATABASE_VERSION = 1; private static TwitterDatabase instance = null; private static DatabaseHelper mOpenHelper = null; private Context mContext = null; /** * SQLiteOpenHelper * */ private static class DatabaseHelper extends SQLiteOpenHelper { // Construct public DatabaseHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } public DatabaseHelper(Context context, String name) { this(context, name, DATABASE_VERSION); } public DatabaseHelper(Context context) { this(context, DATABASE_NAME, DATABASE_VERSION); } public DatabaseHelper(Context context, int version) { this(context, DATABASE_NAME, null, version); } public DatabaseHelper(Context context, String name, int version) { this(context, name, null, version); } @Override public void onCreate(SQLiteDatabase db) { Log.i(TAG, "Create Database."); // Log.i(TAG, StatusTable.STATUS_TABLE_CREATE); db.execSQL(StatusTable.CREATE_TABLE); db.execSQL(MessageTable.CREATE_TABLE); db.execSQL(FollowTable.CREATE_TABLE); //2011.03.01 add beta db.execSQL(UserInfoTable.CREATE_TABLE); } @Override public synchronized void close() { Log.i(TAG, "Close Database."); super.close(); } @Override public void onOpen(SQLiteDatabase db) { Log.i(TAG, "Open Database."); super.onOpen(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.i(TAG, "Upgrade Database."); dropAllTables(db); } private void dropAllTables(SQLiteDatabase db) { db.execSQL("DROP TABLE IF EXISTS " + StatusTable.TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + MessageTable.TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + FollowTable.TABLE_NAME); //2011.03.01 add db.execSQL("DROP TABLE IF EXISTS "+UserInfoTable.TABLE_NAME); } } private TwitterDatabase(Context context) { mContext = context; mOpenHelper = new DatabaseHelper(context); } public static synchronized TwitterDatabase getInstance(Context context) { if (null == instance) { return new TwitterDatabase(context); } return instance; } // 测试用 public SQLiteOpenHelper getSQLiteOpenHelper() { return mOpenHelper; } public static SQLiteDatabase getDb(boolean writeable) { if (writeable) { return mOpenHelper.getWritableDatabase(); } else { return mOpenHelper.getReadableDatabase(); } } public void close() { if (null != instance) { mOpenHelper.close(); instance = null; } } /** * 清空所有表中数据, 谨慎使用 * */ public void clearData() { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); db.execSQL("DELETE FROM " + StatusTable.TABLE_NAME); db.execSQL("DELETE FROM " + MessageTable.TABLE_NAME); db.execSQL("DELETE FROM " + FollowTable.TABLE_NAME); //2011.03.01 add db.execSQL("DELETE FROM "+UserInfoTable.TABLE_NAME); } /** * 直接删除数据库文件, 调试用 * * @return true if this file was deleted, false otherwise. * @deprecated */ private boolean deleteDatabase() { File dbFile = mContext.getDatabasePath(DATABASE_NAME); return dbFile.delete(); } /** * 取出某类型的一条消息 * * @param tweetId * @param type of status * <li>StatusTable.TYPE_HOME</li> * <li>StatusTable.TYPE_MENTION</li> * <li>StatusTable.TYPE_USER</li> * <li>StatusTable.TYPE_FAVORITE</li> * <li>-1 means all types</li> * @return 将Cursor转换过的Tweet对象 */ public Tweet queryTweet(String tweetId, int type) { SQLiteDatabase Db = mOpenHelper.getWritableDatabase(); String selection = StatusTable._ID + "=? "; if (-1 != type) { selection += " AND " + StatusTable.FIELD_STATUS_TYPE + "=" + type; } Cursor cursor = Db.query(StatusTable.TABLE_NAME, StatusTable.TABLE_COLUMNS, selection, new String[] { tweetId }, null, null, null); Tweet tweet = null; if (cursor != null) { cursor.moveToFirst(); if (cursor.getCount() > 0) { tweet = StatusTable.parseCursor(cursor); } } cursor.close(); return tweet; } /** * 快速检查某条消息是否存在(指定类型) * * @param tweetId * @param type * <li>StatusTable.TYPE_HOME</li> * <li>StatusTable.TYPE_MENTION</li> * <li>StatusTable.TYPE_USER</li> * <li>StatusTable.TYPE_FAVORITE</li> * @return is exists */ public boolean isExists(String tweetId, String owner, int type) { SQLiteDatabase Db = mOpenHelper.getWritableDatabase(); boolean result = false; Cursor cursor = Db.query(StatusTable.TABLE_NAME, new String[] { StatusTable._ID }, StatusTable._ID + " =? AND " + StatusTable.FIELD_OWNER_ID + "=? AND " + StatusTable.FIELD_STATUS_TYPE + " = " + type, new String[] { tweetId, owner }, null, null, null); if (cursor != null && cursor.getCount() > 0) { result = true; } cursor.close(); return result; } /** * 删除一条消息 * * @param tweetId * @param type -1 means all types * @return the number of rows affected if a whereClause is passed in, 0 * otherwise. To remove all rows and get a count pass "1" as the * whereClause. */ public int deleteTweet(String tweetId, String owner, int type) { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); String where = StatusTable._ID + " =? "; if (!Utils.isEmpty(owner)){ where += " AND " + StatusTable.FIELD_OWNER_ID + " = '" + owner + "' "; } if (-1 != type) { where += " AND " + StatusTable.FIELD_STATUS_TYPE + " = " + type; } return db.delete(StatusTable.TABLE_NAME, where, new String[] { tweetId }); } /** * 删除超过MAX_ROW_NUM垃圾数据 * * @param type * <li>StatusTable.TYPE_HOME</li> * <li>StatusTable.TYPE_MENTION</li> * <li>StatusTable.TYPE_USER</li> * <li>StatusTable.TYPE_FAVORITE</li> * <li>-1 means all types</li> */ public void gc(String owner, int type) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); String sql = "DELETE FROM " + StatusTable.TABLE_NAME + " WHERE " + StatusTable._ID + " NOT IN " + " (SELECT " + StatusTable._ID // 子句 + " FROM " + StatusTable.TABLE_NAME; boolean first = true; if (!Utils.isEmpty(owner)){ sql += " WHERE " + StatusTable.FIELD_OWNER_ID + " = '" + owner + "' "; first = false; } if (type != -1){ if (first){ sql += " WHERE "; }else{ sql += " AND "; } sql += StatusTable.FIELD_STATUS_TYPE + " = " + type + " "; } sql += " ORDER BY " + StatusTable.FIELD_CREATED_AT + " DESC LIMIT " + StatusTable.MAX_ROW_NUM + ")"; if (!Utils.isEmpty(owner)){ sql += " AND " + StatusTable.FIELD_OWNER_ID + " = '" + owner + "' "; } if (type != -1) { sql += " AND " + StatusTable.FIELD_STATUS_TYPE + " = " + type + " "; } Log.d(TAG, sql); mDb.execSQL(sql); } public final static DateFormat DB_DATE_FORMATTER = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US); /** * 向Status表中写入一行数据, 此方法为私有方法, 外部插入数据请使用 putTweets() * * @param tweet * 需要写入的单条消息 * @return the row ID of the newly inserted row, or -1 if an error occurred */ public long insertTweet(Tweet tweet, String owner, int type, boolean isUnread) { SQLiteDatabase Db = mOpenHelper.getWritableDatabase(); if (isExists(tweet.id, owner, type)) { Log.i(TAG, tweet.id + "is exists."); return -1; } ContentValues initialValues = makeTweetValues(tweet, owner, type, isUnread); long id = Db.insert(StatusTable.TABLE_NAME, null, initialValues); if (-1 == id) { Log.e(TAG, "cann't insert the tweet : " + tweet.toString()); } else { Log.i(TAG, "Insert a status into datebase : " + tweet.toString()); } return id; } /** * 更新一条消息 * * @param tweetId * @param values * ContentValues 需要更新字段的键值对 * @return the number of rows affected */ public int updateTweet(String tweetId, ContentValues values) { Log.i(TAG, "Update Tweet : " + tweetId + " " + values.toString()); SQLiteDatabase Db = mOpenHelper.getWritableDatabase(); return Db.update(StatusTable.TABLE_NAME, values, StatusTable._ID + "=?", new String[] { tweetId }); } private ContentValues makeTweetValues(Tweet tweet, String owner, int type, boolean isUnread) { // 插入一条新消息 ContentValues initialValues = new ContentValues(); initialValues.put(StatusTable.FIELD_OWNER_ID, owner); initialValues.put(StatusTable.FIELD_STATUS_TYPE, type); initialValues.put(StatusTable._ID, tweet.id); initialValues.put(StatusTable.FIELD_TEXT, tweet.text); initialValues.put(StatusTable.FIELD_USER_ID, tweet.userId); initialValues.put(StatusTable.FIELD_USER_SCREEN_NAME, tweet.screenName); initialValues.put(StatusTable.FIELD_PROFILE_IMAGE_URL, tweet.profileImageUrl); initialValues.put(StatusTable.FIELD_PIC_THUMB, tweet.thumbnail_pic); initialValues.put(StatusTable.FIELD_PIC_MID, tweet.bmiddle_pic); initialValues.put(StatusTable.FIELD_PIC_ORIG, tweet.original_pic); initialValues.put(StatusTable.FIELD_FAVORITED, tweet.favorited); initialValues.put(StatusTable.FIELD_IN_REPLY_TO_STATUS_ID, tweet.inReplyToStatusId); initialValues.put(StatusTable.FIELD_IN_REPLY_TO_USER_ID, tweet.inReplyToUserId); initialValues.put(StatusTable.FIELD_IN_REPLY_TO_SCREEN_NAME, tweet.inReplyToScreenName); // initialValues.put(FIELD_IS_REPLY, tweet.isReply()); initialValues.put(StatusTable.FIELD_CREATED_AT, DB_DATE_FORMATTER.format(tweet.createdAt)); initialValues.put(StatusTable.FIELD_SOURCE, tweet.source); initialValues.put(StatusTable.FIELD_IS_UNREAD, isUnread); initialValues.put(StatusTable.FIELD_TRUNCATED, tweet.truncated); // TODO: truncated return initialValues; } /** * 写入N条消息 * * @param tweets * 需要写入的消息List * @return * 写入的记录条数 */ public int putTweets(List<Tweet> tweets, String owner, int type, boolean isUnread) { //long start = System.currentTimeMillis(); if (null == tweets || 0 == tweets.size()) { return 0; } SQLiteDatabase db = mOpenHelper.getWritableDatabase(); int result = 0; try { db.beginTransaction(); for (int i = tweets.size() - 1; i >= 0; i--) { Tweet tweet = tweets.get(i); ContentValues initialValues = makeTweetValues(tweet, owner, type, isUnread); long id = db.insert(StatusTable.TABLE_NAME, null, initialValues); if (-1 == id) { Log.e(TAG, "cann't insert the tweet : " + tweet.toString()); } else { ++result; Log.i(TAG, String.format("Insert a status into database[%s] : %s", owner, tweet.toString())); } } // gc(type); // 保持总量 db.setTransactionSuccessful(); } finally { db.endTransaction(); } return result; //long end = System.currentTimeMillis(); //Log.d("LDS", "putTweets : " + (end-start)); } /** * 取出指定用户的某一类型的所有消息 * * @param userId * @param tableName * @return a cursor */ public Cursor fetchAllTweets(String owner, int type) { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); return mDb.query(StatusTable.TABLE_NAME, StatusTable.TABLE_COLUMNS, StatusTable.FIELD_OWNER_ID + " = ? AND " + StatusTable.FIELD_STATUS_TYPE + " = " + type, new String[]{owner}, null, null, StatusTable.FIELD_CREATED_AT + " DESC "); //LIMIT " + StatusTable.MAX_ROW_NUM); } /** * 取出自己的某一类型的所有消息 * * @param tableName * @return a cursor */ public Cursor fetchAllTweets(int type) { // 获取登录用户id SharedPreferences preferences = TwitterApplication.mPref; String myself = preferences.getString(Preferences.CURRENT_USER_ID, TwitterApplication.mApi.getUserId()); return fetchAllTweets(myself, type); } /** * 清空某类型的所有信息 * * @param tableName * @return the number of rows affected if a whereClause is passed in, 0 * otherwise. To remove all rows and get a count pass "1" as the * whereClause. */ public int dropAllTweets(int type) { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); return mDb.delete(StatusTable.TABLE_NAME, StatusTable.FIELD_STATUS_TYPE + " = " + type, null); } /** * 取出本地某类型最新消息ID * * @param type * @return The newest Status Id */ public String fetchMaxTweetId(String owner, int type) { return fetchMaxOrMinTweetId(owner, type, true); } /** * 取出本地某类型最旧消息ID * * @param tableName * @return The oldest Status Id */ public String fetchMinTweetId(String owner, int type) { return fetchMaxOrMinTweetId(owner, type, false); } private String fetchMaxOrMinTweetId(String owner, int type, boolean isMax) { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); String sql = "SELECT " + StatusTable._ID + " FROM " + StatusTable.TABLE_NAME + " WHERE " + StatusTable.FIELD_STATUS_TYPE + " = " + type + " AND " + StatusTable.FIELD_OWNER_ID + " = '" + owner + "' " + " ORDER BY " + StatusTable.FIELD_CREATED_AT; if (isMax) sql += " DESC "; Cursor mCursor = mDb.rawQuery(sql + " LIMIT 1", null); String result = null; if (mCursor == null) { return result; } mCursor.moveToFirst(); if (mCursor.getCount() == 0) { result = null; } else { result = mCursor.getString(0); } mCursor.close(); return result; } /** * Count unread tweet * * @param tableName * @return */ public int fetchUnreadCount(String owner, int type) { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + StatusTable._ID + ")" + " FROM " + StatusTable.TABLE_NAME + " WHERE " + StatusTable.FIELD_STATUS_TYPE + " = " + type + " AND " + StatusTable.FIELD_OWNER_ID + " = '" + owner + "' AND " + StatusTable.FIELD_IS_UNREAD + " = 1 ", // "LIMIT " + StatusTable.MAX_ROW_NUM, null); int result = 0; if (mCursor == null) { return result; } mCursor.moveToFirst(); result = mCursor.getInt(0); mCursor.close(); return result; } public int addNewTweetsAndCountUnread(List<Tweet> tweets, String owner, int type) { putTweets(tweets, owner, type, true); return fetchUnreadCount(owner, type); } /** * Set isFavorited * * @param tweetId * @param isFavorited * @return Is Succeed */ public boolean setFavorited(String tweetId, String isFavorited) { ContentValues values = new ContentValues(); values.put(StatusTable.FIELD_FAVORITED, isFavorited); int i = updateTweet(tweetId, values); return (i > 0) ? true : false; } // DM & Follower /** * 写入一条私信 * * @param dm * @param isUnread * @return the row ID of the newly inserted row, or -1 if an error occurred, * 因为主键的原因,此处返回的不是 _ID 的值, 而是一个自增长的 row_id */ public long createDm(Dm dm, boolean isUnread) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); ContentValues initialValues = new ContentValues(); initialValues.put(MessageTable._ID, dm.id); initialValues.put(MessageTable.FIELD_USER_SCREEN_NAME, dm.screenName); initialValues.put(MessageTable.FIELD_TEXT, dm.text); initialValues.put(MessageTable.FIELD_PROFILE_IMAGE_URL, dm.profileImageUrl); initialValues.put(MessageTable.FIELD_IS_UNREAD, isUnread); initialValues.put(MessageTable.FIELD_IS_SENT, dm.isSent); initialValues.put(MessageTable.FIELD_CREATED_AT, DB_DATE_FORMATTER.format(dm.createdAt)); initialValues.put(MessageTable.FIELD_USER_ID, dm.userId); return mDb.insert(MessageTable.TABLE_NAME, null, initialValues); } // /** * Create a follower * * @param userId * @return the row ID of the newly inserted row, or -1 if an error occurred */ public long createFollower(String userId) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); ContentValues initialValues = new ContentValues(); initialValues.put(FollowTable._ID, userId); long rowId = mDb.insert(FollowTable.TABLE_NAME, null, initialValues); if (-1 == rowId) { Log.e(TAG, "Cann't create Follower : " + userId); } else { Log.i(TAG, "create create follower : " + userId); } return rowId; } /** * 清空Followers表并添加新内容 * * @param followers */ public void syncFollowers(List<String> followers) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); try { mDb.beginTransaction(); boolean result = deleteAllFollowers(); Log.d(TAG, "Result of DeleteAllFollowers: " + result); for (String userId : followers) { createFollower(userId); } mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } } /** * @param type * <li>MessageTable.TYPE_SENT</li> * <li>MessageTable.TYPE_GET</li> * <li>其他任何值都认为取出所有类型</li> * @return */ public Cursor fetchAllDms(int type) { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); String selection = null; if (MessageTable.TYPE_SENT == type) { selection = MessageTable.FIELD_IS_SENT + " = " + MessageTable.TYPE_SENT; } else if (MessageTable.TYPE_GET == type) { selection = MessageTable.FIELD_IS_SENT + " = " + MessageTable.TYPE_GET; } return mDb.query(MessageTable.TABLE_NAME, MessageTable.TABLE_COLUMNS, selection, null, null, null, MessageTable.FIELD_CREATED_AT + " DESC"); } public Cursor fetchInboxDms() { return fetchAllDms(MessageTable.TYPE_GET); } public Cursor fetchSendboxDms() { return fetchAllDms(MessageTable.TYPE_SENT); } public Cursor fetchAllFollowers() { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); return mDb.query(FollowTable.TABLE_NAME, FollowTable.TABLE_COLUMNS, null, null, null, null, null); } /** * FIXME: * @param filter * @return */ public Cursor getFollowerUsernames(String filter) { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); String likeFilter = '%' + filter + '%'; // FIXME: 此方法的作用应该是在于在写私信时自动完成联系人的功能, // 改造数据库后,因为本地tweets表中的数据有限, 所以几乎使得该功能没有实际价值(因为能从数据库中读到的联系人很少) // 在完成关注者/被关注者两个界面后, 看能不能使得本地有一份 // [互相关注] 的 id/name 缓存(即getFriendsIds和getFollowersIds的交集, 因为客户端只能给他们发私信, 如果按现在 // 只提示followers的列表则很容易造成服务器返回"只能给互相关注的人发私信"的错误信息, 这会造成用户无法理解, 因为此联系人是我们提供给他们选择的, // 并且将目前的自动完成功能的基础上加一个[选择联系人]按钮, 用于启动一个新的联系人列表页面以显示所有可发送私信的联系人对象, 类似手机写短信时的选择联系人功能 return null; // FIXME: clean this up. 新数据库中失效, 表名, 列名 // return mDb.rawQuery( // "SELECT user_id AS _id, user" // + " FROM (SELECT user_id, user FROM tweets" // + " INNER JOIN followers on tweets.user_id = followers._id UNION" // + " SELECT user_id, user FROM dms INNER JOIN followers" // + " on dms.user_id = followers._id)" // + " WHERE user LIKE ?" // + " ORDER BY user COLLATE NOCASE", // new String[] { likeFilter }); } /** * @param userId * 该用户是否follow Me * @deprecated 未使用 * @return */ public boolean isFollower(String userId) { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); Cursor cursor = mDb.query(FollowTable.TABLE_NAME, FollowTable.TABLE_COLUMNS, FollowTable._ID + "= ?", new String[] { userId }, null, null, null); boolean result = false; if (cursor != null && cursor.moveToFirst()) { result = true; } cursor.close(); return result; } public boolean deleteAllFollowers() { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); return mDb.delete(FollowTable.TABLE_NAME, null, null) > 0; } public boolean deleteDm(String id) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); return mDb.delete(MessageTable.TABLE_NAME, String.format("%s = '%s'", MessageTable._ID, id), null) > 0; } /** * @param tableName * @return the number of rows affected */ public int markAllTweetsRead(String owner, int type) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(StatusTable.FIELD_IS_UNREAD, 0); return mDb.update(StatusTable.TABLE_NAME, values, StatusTable.FIELD_STATUS_TYPE + "=" + type, null); } public boolean deleteAllDms() { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); return mDb.delete(MessageTable.TABLE_NAME, null, null) > 0; } public int markAllDmsRead() { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(MessageTable.FIELD_IS_UNREAD, 0); return mDb.update(MessageTable.TABLE_NAME, values, null, null); } public String fetchMaxDmId(boolean isSent) { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); Cursor mCursor = mDb.rawQuery("SELECT " + MessageTable._ID + " FROM " + MessageTable.TABLE_NAME + " WHERE " + MessageTable.FIELD_IS_SENT + " = ? " + " ORDER BY " + MessageTable.FIELD_CREATED_AT + " DESC LIMIT 1", new String[] { isSent ? "1" : "0" }); String result = null; if (mCursor == null) { return result; } mCursor.moveToFirst(); if (mCursor.getCount() == 0) { result = null; } else { result = mCursor.getString(0); } mCursor.close(); return result; } public int addNewDmsAndCountUnread(List<Dm> dms) { addDms(dms, true); return fetchUnreadDmCount(); } public int fetchDmCount() { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + MessageTable._ID + ") FROM " + MessageTable.TABLE_NAME, null); int result = 0; if (mCursor == null) { return result; } mCursor.moveToFirst(); result = mCursor.getInt(0); mCursor.close(); return result; } private int fetchUnreadDmCount() { SQLiteDatabase mDb = mOpenHelper.getReadableDatabase(); Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + MessageTable._ID + ") FROM " + MessageTable.TABLE_NAME + " WHERE " + MessageTable.FIELD_IS_UNREAD + " = 1", null); int result = 0; if (mCursor == null) { return result; } mCursor.moveToFirst(); result = mCursor.getInt(0); mCursor.close(); return result; } public void addDms(List<Dm> dms, boolean isUnread) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); try { mDb.beginTransaction(); for (Dm dm : dms) { createDm(dm, isUnread); } // limitRows(TABLE_DIRECTMESSAGE, TwitterApi.RETRIEVE_LIMIT); mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } } //2011.03.01 add //UserInfo操作 public Cursor getAllUserInfo(){ SQLiteDatabase mDb=mOpenHelper.getReadableDatabase(); return mDb.query(UserInfoTable.TABLE_NAME,UserInfoTable.TABLE_COLUMNS, null, null, null, null, null); } /** * 根据id列表获取user数据 * @param userIds * @return */ public Cursor getUserInfoByIds(String[] userIds){ SQLiteDatabase mDb=mOpenHelper.getReadableDatabase(); String userIdStr=""; for(String id:userIds){ userIdStr+="'"+id+"',"; } if(userIds.length==0){ userIdStr="'',"; } userIdStr=userIdStr.substring(0, userIdStr.lastIndexOf(","));//删除最后的逗号 return mDb.query(UserInfoTable.TABLE_NAME, UserInfoTable.TABLE_COLUMNS, UserInfoTable._ID+" in ("+userIdStr+")", null, null, null, null); } /** * 新建用户 * * @param user * @return the row ID of the newly inserted row, or -1 if an error occurred */ public long createUserInfo(com.ch_linghu.fanfoudroid.data.User user) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); ContentValues initialValues = new ContentValues(); initialValues.put(UserInfoTable._ID, user.id); initialValues.put(UserInfoTable.FIELD_USER_NAME, user.name); initialValues.put(UserInfoTable.FIELD_USER_SCREEN_NAME, user.screenName); initialValues.put(UserInfoTable.FIELD_LOCALTION, user.location); initialValues.put(UserInfoTable.FIELD_DESCRIPTION, user.description); initialValues.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, user.profileImageUrl); initialValues.put(UserInfoTable.FIELD_URL, user.url); initialValues.put(UserInfoTable.FIELD_PROTECTED, user.isProtected); initialValues.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, user.followersCount); initialValues.put(UserInfoTable.FIELD_LAST_STATUS, user.lastStatus); initialValues.put(UserInfoTable.FIELD_FRIENDS_COUNT, user.friendsCount); initialValues.put(UserInfoTable.FIELD_FAVORITES_COUNT, user.favoritesCount); initialValues.put(UserInfoTable.FIELD_STATUSES_COUNT, user.statusesCount); initialValues.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing); long rowId = mDb.insertWithOnConflict(UserInfoTable.TABLE_NAME, null, initialValues,SQLiteDatabase.CONFLICT_REPLACE); if (-1 == rowId) { Log.e(TAG, "Cann't create Follower : " + user.id); } else { Log.i(TAG, "create create follower : " + user.id); } return rowId; } public long createWeiboUserInfo(com.ch_linghu.fanfoudroid.weibo.User user){ SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); ContentValues args = new ContentValues(); args.put(UserInfoTable._ID, user.getId()); args.put(UserInfoTable.FIELD_USER_NAME, user.getName()); args.put(UserInfoTable.FIELD_USER_SCREEN_NAME, user.getScreenName()); String location = user.getLocation(); args.put(UserInfoTable.FIELD_LOCALTION, location); String description = user.getDescription(); args.put(UserInfoTable.FIELD_DESCRIPTION, description); args.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, user.getProfileBackgroundImageUrl()); if (user.getURL() != null) { args.put(UserInfoTable.FIELD_URL, user.getURL().toString()); } args.put(UserInfoTable.FIELD_PROTECTED, user.isProtected()); args.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, user.getFollowersCount()); args.put(UserInfoTable.FIELD_LAST_STATUS, user.getStatusSource()); args.put(UserInfoTable.FIELD_FRIENDS_COUNT, user.getFriendsCount()); args.put(UserInfoTable.FIELD_FAVORITES_COUNT, user.getFavouritesCount()); args.put(UserInfoTable.FIELD_STATUSES_COUNT, user.getStatusesCount()); args.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing()); //long rowId = mDb.insert(UserInfoTable.TABLE_NAME, null, args); //省去判断existUser,如果存在数据则replace long rowId=mDb.insertWithOnConflict(UserInfoTable.TABLE_NAME, null, args, SQLiteDatabase.CONFLICT_REPLACE); if (-1 == rowId) { Log.e(TAG, "Cann't create Follower : " + user.getId()); } else { Log.i(TAG, "create create follower : " + user.getId()); } return rowId; } /** * 查看数据是否已保存用户数据 * @param userId * @return */ public boolean existsUser(String userId) { SQLiteDatabase Db = mOpenHelper.getReadableDatabase(); boolean result = false; Cursor cursor = Db.query(UserInfoTable.TABLE_NAME, new String[] { UserInfoTable._ID }, UserInfoTable._ID +"='"+userId+"'", null, null, null, null); Log.i("testesetesteste", String.valueOf(cursor.getCount())); if (cursor != null && cursor.getCount() > 0) { result = true; } cursor.close(); return result; } /** * 根据userid提取信息 * @param userId * @return */ public Cursor getUserInfoById(String userId){ SQLiteDatabase Db = mOpenHelper.getReadableDatabase(); Cursor cursor = Db.query(UserInfoTable.TABLE_NAME, UserInfoTable.TABLE_COLUMNS, UserInfoTable._ID + " = '" +userId+"'", null, null, null, null); return cursor; } /** * 更新用户 * @param uid * @param args * @return */ public boolean updateUser(String uid,ContentValues args){ SQLiteDatabase Db=mOpenHelper.getWritableDatabase(); return Db.update(UserInfoTable.TABLE_NAME, args, UserInfoTable._ID+"='"+uid+"'", null)>0; } /** * 更新用户信息 */ public boolean updateUser(com.ch_linghu.fanfoudroid.data.User user){ SQLiteDatabase Db=mOpenHelper.getWritableDatabase(); ContentValues args=new ContentValues(); args.put(UserInfoTable._ID, user.id); args.put(UserInfoTable.FIELD_USER_NAME, user.name); args.put(UserInfoTable.FIELD_USER_SCREEN_NAME, user.screenName); args.put(UserInfoTable.FIELD_LOCALTION, user.location); args.put(UserInfoTable.FIELD_DESCRIPTION, user.description); args.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, user.profileImageUrl); args.put(UserInfoTable.FIELD_URL, user.url); args.put(UserInfoTable.FIELD_PROTECTED, user.isProtected); args.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, user.followersCount); args.put(UserInfoTable.FIELD_LAST_STATUS, user.lastStatus); args.put(UserInfoTable.FIELD_FRIENDS_COUNT, user.friendsCount); args.put(UserInfoTable.FIELD_FAVORITES_COUNT, user.favoritesCount); args.put(UserInfoTable.FIELD_STATUSES_COUNT, user.statusesCount); args.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing); return Db.update(UserInfoTable.TABLE_NAME, args, UserInfoTable._ID+"='"+user.id+"'", null)>0; } /** * 减少转换的开销 * @param user * @return */ public boolean updateWeiboUser(com.ch_linghu.fanfoudroid.weibo.User user){ SQLiteDatabase Db=mOpenHelper.getWritableDatabase(); ContentValues args = new ContentValues(); args.put(UserInfoTable._ID, user.getName()); args.put(UserInfoTable.FIELD_USER_NAME, user.getName()); args.put(UserInfoTable.FIELD_USER_SCREEN_NAME, user.getScreenName()); String location = user.getLocation(); args.put(UserInfoTable.FIELD_LOCALTION, location); String description = user.getDescription(); args.put(UserInfoTable.FIELD_DESCRIPTION, description); args.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, user.getProfileBackgroundImageUrl()); if (user.getURL() != null) { args.put(UserInfoTable.FIELD_URL, user.getURL().toString()); } args.put(UserInfoTable.FIELD_PROTECTED, user.isProtected()); args.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, user.getFollowersCount()); args.put(UserInfoTable.FIELD_LAST_STATUS, user.getStatusSource()); args.put(UserInfoTable.FIELD_FRIENDS_COUNT, user.getFriendsCount()); args.put(UserInfoTable.FIELD_FAVORITES_COUNT, user.getFavouritesCount()); args.put(UserInfoTable.FIELD_STATUSES_COUNT, user.getStatusesCount()); args.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing()); return Db.update(UserInfoTable.TABLE_NAME, args, UserInfoTable._ID+"='"+user.getId()+"'", null)>0; } /** * 同步用户,更新已存在的用户,插入未存在的用户 */ public void syncUsers(List<com.ch_linghu.fanfoudroid.data.User> users){ SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); try{ mDb.beginTransaction(); for(com.ch_linghu.fanfoudroid.data.User u:users){ // if(existsUser(u.id)){ // updateUser(u); // }else{ // createUserInfo(u); // } createUserInfo(u); } mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } } public void syncWeiboUsers(List<com.ch_linghu.fanfoudroid.weibo.User> users) { SQLiteDatabase mDb = mOpenHelper.getWritableDatabase(); try { mDb.beginTransaction(); for (com.ch_linghu.fanfoudroid.weibo.User u : users) { // if (existsUser(u.getId())) { // updateWeiboUser(u); // } else { // createWeiboUserInfo(u); // } createWeiboUserInfo(u); } mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } } }
Java
package com.ch_linghu.fanfoudroid.data; import android.content.ContentValues; import android.database.Cursor; public interface BaseContent { long insert(); int delete(); int update(); Cursor select(); }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Toast; import android.widget.AdapterView.AdapterContextMenuInfo; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.data.db.StatusTable; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.HttpRefusedException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.task.TweetCommonTask; import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity; import com.ch_linghu.fanfoudroid.weibo.Paging; import com.ch_linghu.fanfoudroid.weibo.Status; public class TwitterActivity extends TwitterCursorBaseActivity { private static final String TAG = "TwitterActivity"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.TWEETS"; protected GenericTask mDeleteTask; private TaskListener mDeleteTaskListener = new TaskAdapter() { @Override public String getName() { return "DeleteTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { onDeleteSuccess(); } else if (result == TaskResult.IO_ERROR) { onDeleteFailure(); } } }; static final int DIALOG_WRITE_ID = 0; public static Intent createIntent(Context context) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); return intent; } public static Intent createNewTaskIntent(Context context) { Intent intent = createIntent(context); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); return intent; } @Override protected boolean _onCreate(Bundle savedInstanceState) { if (super._onCreate(savedInstanceState)) { setHeaderTitle("饭否fanfou.com"); return true; } else { return false; } } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING) { mDeleteTask.cancel(true); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } // Menu. @Override public boolean onCreateOptionsMenu(Menu menu) { return super.onCreateOptionsMenu(menu); } private int CONTEXT_DELETE_ID = getLastContextMenuId() + 1; @Override protected int getLastContextMenuId() { return CONTEXT_DELETE_ID; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; Tweet tweet = getContextItemTweet(info.position); if (null != tweet) {// 当按钮为 刷新/更多的时候为空 if (tweet.userId.equals(TwitterApplication.getMyselfId())) { menu.add(0, CONTEXT_DELETE_ID, 0, R.string.cmenu_delete); } } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); Tweet tweet = getContextItemTweet(info.position); if (tweet == null) { Log.w(TAG, "Selected item not available."); return super.onContextItemSelected(item); } if (item.getItemId() == CONTEXT_DELETE_ID) { doDelete(tweet.id); return true; } else { return super.onContextItemSelected(item); } } @Override protected Cursor fetchMessages() { return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_HOME); } @Override protected String getActivityTitle() { return getResources().getString(R.string.page_title_home); } @Override protected void markAllRead() { getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_HOME); } // hasRetrieveListTask interface @Override public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) { // 获取消息的时候,将status里获取的user也存储到数据库 for (Tweet t : tweets) { getDb().createWeiboUserInfo(t.user); } return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_HOME, isUnread); } @Override public String fetchMaxId() { return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_HOME); } @Override public List<Status> getMessageSinceId(String maxId) throws HttpException { if (maxId != null) { return getApi().getFriendsTimeline(new Paging(maxId)); } else { return getApi().getFriendsTimeline(); } } public void onDeleteFailure() { Log.e(TAG, "Delete failed"); } public void onDeleteSuccess() { mTweetAdapter.refresh(); } private void doDelete(String id) { if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mDeleteTask = new TweetCommonTask.DeleteTask(this); mDeleteTask.setListener(mDeleteTaskListener); TaskParams params = new TaskParams(); params.put("id", id); mDeleteTask.execute(params); } } @Override public String fetchMinId() { return getDb().fetchMinTweetId(getUserId(), StatusTable.TYPE_HOME); } @Override public List<Status> getMoreMessageFromId(String minId) throws HttpException { Paging paging = new Paging(1, 20); paging.setMaxId(minId); return getApi().getFriendsTimeline(paging); } @Override public int getDatabaseType() { return StatusTable.TYPE_HOME; } @Override public String getUserId() { return TwitterApplication.getMyselfId(); } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.text.Editable; import android.text.Selection; import android.text.TextWatcher; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.ch_linghu.fanfoudroid.helper.ImageManager; import com.ch_linghu.fanfoudroid.helper.Preferences; import com.ch_linghu.fanfoudroid.helper.Utils; import com.ch_linghu.fanfoudroid.http.HttpClient; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.base.WithHeaderActivity; import com.ch_linghu.fanfoudroid.ui.module.TweetEdit; public class WriteActivity extends WithHeaderActivity { //FIXME: for debug, delete me private long startTime = -1; private long endTime = -1; public static final String NEW_TWEET_ACTION = "com.ch_linghu.fanfoudroid.NEW"; public static final String REPOST_TWEET_ACTION = "com.ch_linghu.fanfoudroid.REPOST"; public static final String EXTRA_TEXT = "text"; public static final String EXTRA_REPLY_ID = "reply_id"; public static final String EXTRA_REPOST_ID = "repost_status_id"; private static final String TAG = "WriteActivity"; private static final String SIS_RUNNING_KEY = "running"; private static final String PREFS_NAME = "com.ch_linghu.fanfoudroid"; private static final int REQUEST_IMAGE_CAPTURE = 2; private static final int REQUEST_PHOTO_LIBRARY = 3; // View private TweetEdit mTweetEdit; private EditText mTweetEditText; private TextView mProgressText; private Button mSendButton; private Button chooseImagesButton; private ProgressDialog dialog; // Picture private boolean withPic = false; private File mFile; private ImageView mPreview; private static final int MAX_BITMAP_SIZE = 400; private File mImageFile; private Uri mImageUri; // Task private GenericTask mSendTask; private TaskListener mSendTaskListener = new TaskAdapter(){ @Override public void onPreExecute(GenericTask task) { onSendBegin(); } @Override public void onPostExecute(GenericTask task, TaskResult result) { endTime = System.currentTimeMillis(); Log.d("LDS", "Sended a status in " + (endTime - startTime)); if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { onSendSuccess(); } else if (result == TaskResult.IO_ERROR) { onSendFailure(); } } @Override public String getName() { // TODO Auto-generated method stub return "SendTask"; } }; private String _reply_id; private String _repost_id; // sub menu protected void openImageCaptureMenu() { try { // TODO: API < 1.6, images size too small mImageFile = new File(Environment.getExternalStorageDirectory(), "upload.jpg"); mImageUri = Uri.fromFile(mImageFile); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri); startActivityForResult(intent, REQUEST_IMAGE_CAPTURE); } catch (Exception e) { Log.e(TAG, e.getMessage()); } } protected void openPhotoLibraryMenu() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); startActivityForResult(intent, REQUEST_PHOTO_LIBRARY); } protected void createInsertPhotoDialog() { final CharSequence[] items = { getString(R.string.write_label_take_a_picture), getString(R.string.write_label_choose_a_picture) }; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getString(R.string.write_label_insert_picture)); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { switch (item) { case 0: openImageCaptureMenu(); break; case 1: openPhotoLibraryMenu(); } } }); AlertDialog alert = builder.create(); alert.show(); } private void getPic(Intent intent, Uri uri) { // Cann't insert two pictures chooseImagesButton.setEnabled(false); // layout for picture mode changeStyleWithPic(); withPic = true; mFile = null; if (uri.getScheme().equals("content")){ mImageUri = uri; } else { //suppose that we got a file:// URI, convert it to content:// URI String path = uri.getPath(); File file = new File(path); mImageUri = Uri.fromFile(file); } //String filename = extras.getString("filename"); //mFile = new File(filename); //TODO: 需要进一步细化 //TODO:想将图片放在EditText左边 mFile = bitmapToFile(createThumbnailBitmap(mImageUri, 800)); mPreview.setImageBitmap(createThumbnailBitmap(mImageUri, MAX_BITMAP_SIZE)); if (mFile == null) { updateProgress("Could not locate picture file. Sorry!"); disableEntry(); } } private File bitmapToFile(Bitmap bitmap) { File file = new File(Environment.getExternalStorageDirectory(), "upload.jpg"); try { FileOutputStream out=new FileOutputStream(file); if(bitmap.compress(Bitmap.CompressFormat.JPEG, 80, out)){ out.flush(); out.close(); } } catch (FileNotFoundException e) { Log.e(TAG, "Sorry, the file can not be created"); return null; } catch (IOException e) { Log.e(TAG, "IOException occurred when save upload file"); return null; } return file; } private void changeStyleWithPic() { //修改布局 ,以前 图片居中,现在在左边 // mPreview.setLayoutParams( // new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT) // ); mPreview.setVisibility(View.VISIBLE); mTweetEditText.setLayoutParams( new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 2f) ); } /** * 制作微缩图 * @param uri * @param size * @return */ private Bitmap createThumbnailBitmap(Uri uri, int size) { InputStream input = null; try { input = getContentResolver().openInputStream(uri); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(input, null, options); input.close(); // Compute the scale. int scale = 1; while ((options.outWidth / scale > size) || (options.outHeight / scale > size)) { scale *= 2; } options.inJustDecodeBounds = false; options.inSampleSize = scale; input = getContentResolver().openInputStream(uri); return BitmapFactory.decodeStream(input, null, options); } catch (IOException e) { Log.w(TAG, e); return null; } finally { if (input != null) { try { input.close(); } catch (IOException e) { Log.w(TAG, e); } } } } @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.i(TAG, "onCreate."); if (super._onCreate(savedInstanceState)){ // init View setContentView(R.layout.write); initHeader(HEADER_STYLE_WRITE); // Intent & Action & Extras Intent intent = getIntent(); String action = intent.getAction(); Bundle extras = intent.getExtras(); String text = null; Uri uri = null; if(extras != null){ text = extras.getString(Intent.EXTRA_TEXT); uri = (Uri)(extras.get(Intent.EXTRA_STREAM)); } _reply_id = null; _repost_id = null; // View mProgressText = (TextView) findViewById(R.id.progress_text); mTweetEditText = (EditText) findViewById(R.id.tweet_edit); // 插入图片 chooseImagesButton = (Button) findViewById(R.id.choose_images_button); chooseImagesButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Log.i(TAG, "chooseImagesButton onClick"); createInsertPhotoDialog(); } }); // With picture mPreview = (ImageView) findViewById(R.id.preview); if (Intent.ACTION_SEND.equals(intent.getAction()) && uri != null) { getPic(intent, uri); } // Update status mTweetEdit = new TweetEdit(mTweetEditText, (TextView) findViewById(R.id.chars_text)); mTweetEdit.setOnKeyListener(tweetEnterHandler); mTweetEdit .addTextChangedListener(new MyTextWatcher(WriteActivity.this)); mTweetEdit.setText(text); if (NEW_TWEET_ACTION.equals(action)) { _reply_id = intent.getStringExtra(EXTRA_REPLY_ID); } if (REPOST_TWEET_ACTION.equals(action)) { // 根据用户习惯,将光标放置在转发消息的头部或尾部 SharedPreferences prefereces = getPreferences(); boolean isAppendToTheBeginning = prefereces.getBoolean(Preferences.RT_INSERT_APPEND, true); EditText inputField = mTweetEdit.getEditText(); inputField.setTextKeepState(text); Editable etext = inputField.getText(); int position = (isAppendToTheBeginning) ? 1 : etext.length(); Selection.setSelection(etext, position); } mSendButton = (Button) findViewById(R.id.send_button); mSendButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { doSend(); } }); return true; }else{ return false; } } @Override protected void onPause() { super.onPause(); Log.i(TAG, "onPause."); } @Override protected void onRestart() { super.onRestart(); Log.i(TAG, "onRestart."); } @Override protected void onResume() { super.onResume(); Log.i(TAG, "onResume."); } @Override protected void onStart() { super.onStart(); Log.i(TAG, "onStart."); } @Override protected void onStop() { super.onStop(); Log.i(TAG, "onStop."); } @Override protected void onDestroy() { Log.i(TAG, "onDestroy."); if (mSendTask != null && mSendTask.getStatus() == GenericTask.Status.RUNNING) { // Doesn't really cancel execution (we let it continue running). // See the SendTask code for more details. mSendTask.cancel(true); } // Don't need to cancel FollowersTask (assuming it ends properly). if (dialog != null){ dialog.dismiss(); } super.onDestroy(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mSendTask != null && mSendTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } public static Intent createNewTweetIntent(String text) { Intent intent = new Intent(NEW_TWEET_ACTION); intent.putExtra(Intent.EXTRA_TEXT, text); return intent; } public static Intent createNewReplyIntent(String screenName, String replyId) { String replyTo = "@" + screenName + " "; Intent intent = new Intent(WriteActivity.NEW_TWEET_ACTION); intent.putExtra(Intent.EXTRA_TEXT, replyTo); intent.putExtra(WriteActivity.EXTRA_REPLY_ID, replyId); return intent; } public static Intent createNewRepostIntent(Context content, String tweetText, String screenName, String repostId) { SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(content); String prefix = mPreferences.getString(Preferences.RT_PREFIX_KEY, content.getString(R.string.pref_rt_prefix_default)); String retweet = " " + prefix + " @" + screenName + " " + Utils.getSimpleTweetText(tweetText); Intent intent = new Intent(WriteActivity.REPOST_TWEET_ACTION); intent.putExtra(Intent.EXTRA_TEXT, retweet); intent.putExtra(WriteActivity.EXTRA_REPOST_ID, repostId); return intent; } public static Intent createImageIntent(Activity activity, Uri uri){ Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_STREAM, uri); try{ WriteActivity writeActivity = (WriteActivity)activity; intent.putExtra(Intent.EXTRA_TEXT, writeActivity.mTweetEdit.getText()); intent.putExtra(WriteActivity.EXTRA_REPLY_ID, writeActivity._reply_id); intent.putExtra(WriteActivity.EXTRA_REPOST_ID, writeActivity._repost_id); }catch(ClassCastException e){ //do nothing } return intent; } private class MyTextWatcher implements TextWatcher { private WriteActivity _activity; public MyTextWatcher(WriteActivity activity) { _activity = activity; } @Override public void afterTextChanged(Editable s) { if (s.length() == 0) { _activity._reply_id = null; _activity._repost_id = null; } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } } private View.OnKeyListener tweetEnterHandler = new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { if (event.getAction() == KeyEvent.ACTION_UP) { WriteActivity t = (WriteActivity) (v.getContext()); doSend(); } return true; } return false; } }; private void doSend() { startTime = System.currentTimeMillis() ; Log.i(TAG, String.format("doSend, reply_id=%s", _reply_id)); if (mSendTask != null && mSendTask.getStatus() == GenericTask.Status.RUNNING){ return; }else{ String status = mTweetEdit.getText().toString(); if (! Utils.isEmpty(status) || withPic) { int mode = SendTask.TYPE_NORMAL; if (withPic) { mode = SendTask.TYPE_PHOTO; } else if (null != _reply_id) { mode = SendTask.TYPE_REPLY; } else if (null != _repost_id) { mode = SendTask.TYPE_REPOST; } mSendTask = new SendTask(); mSendTask.setListener(mSendTaskListener); TaskParams params = new TaskParams(); params.put("mode", mode); mSendTask.execute(params); } else { updateProgress(getString(R.string.page_text_is_null)); } } } private class SendTask extends GenericTask { public static final int TYPE_NORMAL = 0; public static final int TYPE_REPLY = 1; public static final int TYPE_REPOST = 2; public static final int TYPE_PHOTO = 3; @Override protected TaskResult _doInBackground(TaskParams...params) { TaskParams param = params[0]; try { String status = mTweetEdit.getText().toString(); int mode = param.getInt("mode"); Log.i(TAG, "Send Status. Mode : " + mode); // Send status in different way switch (mode) { case TYPE_REPLY: //增加容错性,即使reply_id为空依然允许发送 if (null == WriteActivity.this._reply_id) { Log.e(TAG, "Cann't send status in REPLY mode, reply_id is null"); } getApi().updateStatus(status, WriteActivity.this._reply_id); break; case TYPE_REPOST: //增加容错性,即使repost_id为空依然允许发送 if (null == WriteActivity.this._repost_id) { Log.e(TAG, "Cann't send status in REPOST mode, repost_id is null"); } getApi().repost(status, WriteActivity.this._repost_id); break; case TYPE_PHOTO: if (null != mFile) { // Compress image try { mFile = getImageManager().compressImage(mFile, 90); } catch (IOException ioe) { Log.e(TAG, "Cann't compress images."); } getApi().updateStatus(status, mFile); } else { Log.e(TAG, "Cann't send status in PICTURE mode, photo is null"); } break; case TYPE_NORMAL: default: getApi().updateStatus(status); // just send a status break; } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); if (e.getStatusCode() == HttpClient.NOT_AUTHORIZED) { return TaskResult.AUTH_ERROR; } return TaskResult.IO_ERROR; } return TaskResult.OK; } private ImageManager getImageManager() { return TwitterApplication.mProfileImageCacheManager.getImageManager(); } } private void onSendBegin() { disableEntry(); dialog = ProgressDialog.show(WriteActivity.this, "", getString(R.string.page_status_updating), true); if (dialog != null){ dialog.setCancelable(false); } updateProgress(getString(R.string.page_status_updating)); } private void onSendSuccess() { if (dialog != null){ dialog.setMessage(getString(R.string.page_status_update_success)); dialog.dismiss(); } _reply_id = null; _repost_id = null; updateProgress(getString(R.string.page_status_update_success)); enableEntry(); //FIXME: 不理解这段代码的含义,暂时注释掉 // try { // Thread.currentThread(); // Thread.sleep(500); // updateProgress(""); // } catch (InterruptedException e) { // Log.i(TAG, e.getMessage()); // } updateProgress(""); //发送成功就自动关闭界面 finish(); // 关闭软键盘 InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mTweetEdit.getEditText().getWindowToken(), 0); } private void onSendFailure() { dialog.setMessage(getString(R.string.page_status_unable_to_update)); dialog.dismiss(); updateProgress(getString(R.string.page_status_unable_to_update)); enableEntry(); } private void enableEntry() { mTweetEdit.setEnabled(true); mSendButton.setEnabled(true); chooseImagesButton.setEnabled(true); } private void disableEntry() { mTweetEdit.setEnabled(false); mSendButton.setEnabled(false); chooseImagesButton.setEnabled(false); } // UI helpers. private void updateProgress(String progress) { mProgressText.setText(progress); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK){ Intent intent = WriteActivity.createImageIntent(this, mImageUri); intent.setClass(this, WriteActivity.class); startActivity(intent); //打开发送图片界面后将自身关闭 finish(); } else if (requestCode == REQUEST_PHOTO_LIBRARY && resultCode == RESULT_OK){ mImageUri = data.getData(); Intent intent = WriteActivity.createImageIntent(this, mImageUri); intent.setClass(this, WriteActivity.class); startActivity(intent); //打开发送图片界面后将自身关闭 finish(); } } }
Java
package com.ch_linghu.fanfoudroid; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Timer; import java.util.TimerTask; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.data.db.StatusTable; import com.ch_linghu.fanfoudroid.data.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.helper.ProfileImageCacheCallback; import com.ch_linghu.fanfoudroid.helper.Utils; import com.ch_linghu.fanfoudroid.service.TwitterService; import com.ch_linghu.fanfoudroid.service.WidgetService; import android.app.ActivityManager; import android.app.PendingIntent; import android.app.ActivityManager.RunningServiceInfo; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Intent; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.text.Html; import android.text.Spanned; import android.util.Log; import android.widget.RemoteViews; import android.appwidget.AppWidgetManager; public class FanfouWidget extends AppWidgetProvider { public final String TAG = "com.ch_linghu.fanfoudroid.FanfouWidget"; public final String NEXTACTION = "com.ch_linghu.fanfoudroid.FanfouWidget.NEXT"; public final String PREACTION = "com.ch_linghu.fanfoudroid.FanfouWidget.PREV"; private static List<Tweet> tweets; private static int position = 0; class CacheCallback implements ProfileImageCacheCallback { private RemoteViews updateViews; CacheCallback(RemoteViews updateViews) { this.updateViews = updateViews; } @Override public void refresh(String url, Bitmap bitmap) { updateViews.setImageViewBitmap(R.id.status_image, bitmap); } } @Override public void onUpdate(Context context, AppWidgetManager appwidgetmanager, int[] appWidgetIds) { Log.i(TAG, "onUpdate"); TwitterService.setWidgetStatus(true); // if (!isRunning(context, WidgetService.class.getName())) { // Intent i = new Intent(context, WidgetService.class); // context.startService(i); // } update(context); } private void update(Context context) { fetchMessages(); position = 0; refreshView(context, NEXTACTION); } private TwitterDatabase getDb() { return TwitterApplication.mDb; } public String getUserId() { return TwitterApplication.getMyselfId(); } private void fetchMessages() { if (tweets == null) { tweets = new ArrayList<Tweet>(); } else { tweets.clear(); } Cursor cursor = getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_HOME); if (cursor != null) { if (cursor.moveToFirst()) { do { Tweet tweet = StatusTable.parseCursor(cursor); tweets.add(tweet); } while (cursor.moveToNext()); } } Log.d(TAG, "Tweets size " + tweets.size()); } private void refreshView(Context context, String action) { //某些情况下,tweets会为null if(tweets==null){ fetchMessages(); } //防止引发IndexOutOfBoundsException if (tweets.size() != 0) { if (action.equals(NEXTACTION)) { --position; } else if (action.equals(PREACTION)) { ++position; } // Log.d(TAG, "Tweets size =" + tweets.size()); if (position >= tweets.size() || position < 0) { position = 0; } // Log.d(TAG, "position=" + position); ComponentName fanfouWidget = new ComponentName(context, FanfouWidget.class); AppWidgetManager manager = AppWidgetManager.getInstance(context); manager.updateAppWidget(fanfouWidget, buildUpdate(context)); } } public RemoteViews buildUpdate(Context context) { RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_initial_layout); Tweet t = tweets.get(position); Log.d(TAG, "tweet=" + t); updateViews.setTextViewText(R.id.status_screen_name, t.screenName); updateViews.setTextViewText(R.id.status_text, Utils.getSimpleTweetText(t.text)); updateViews.setTextViewText(R.id.tweet_source, context.getString(R.string.tweet_source_prefix) + t.source); updateViews.setTextViewText(R.id.tweet_created_at, Utils.getRelativeDate(t.createdAt)); updateViews.setImageViewBitmap(R.id.status_image, TwitterApplication.mProfileImageCacheManager.get( t.profileImageUrl, new CacheCallback(updateViews))); Intent inext = new Intent(context, FanfouWidget.class); inext.setAction(NEXTACTION); PendingIntent pinext = PendingIntent.getBroadcast(context, 0, inext, PendingIntent.FLAG_UPDATE_CURRENT); updateViews.setOnClickPendingIntent(R.id.btn_next, pinext); Intent ipre = new Intent(context, FanfouWidget.class); ipre.setAction(PREACTION); PendingIntent pipre = PendingIntent.getBroadcast(context, 0, ipre, PendingIntent.FLAG_UPDATE_CURRENT); updateViews.setOnClickPendingIntent(R.id.btn_pre, pipre); Intent write = WriteActivity.createNewTweetIntent(""); PendingIntent piwrite = PendingIntent.getActivity(context, 0, write, PendingIntent.FLAG_UPDATE_CURRENT); updateViews.setOnClickPendingIntent(R.id.write_message, piwrite); Intent home = TwitterActivity.createIntent(context); PendingIntent pihome = PendingIntent.getActivity(context, 0, home, PendingIntent.FLAG_UPDATE_CURRENT); updateViews.setOnClickPendingIntent(R.id.logo_image, pihome); Intent status = StatusActivity.createIntent(t); PendingIntent pistatus = PendingIntent.getActivity(context, 0, status, PendingIntent.FLAG_UPDATE_CURRENT); updateViews.setOnClickPendingIntent(R.id.main_body, pistatus); return updateViews; } @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "OnReceive"); super.onReceive(context, intent); String action = intent.getAction(); Log.i(TAG, "action is" + intent.getAction()); if (NEXTACTION.equals(action) || PREACTION.equals(action)) { refreshView(context, intent.getAction()); } else if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) { update(context); } } /** * * @param c * @param serviceName * @return */ @Deprecated public boolean isRunning(Context c, String serviceName) { ActivityManager myAM = (ActivityManager) c .getSystemService(Context.ACTIVITY_SERVICE); ArrayList<RunningServiceInfo> runningServices = (ArrayList<RunningServiceInfo>) myAM .getRunningServices(40); // 获取最多40个当前正在运行的服务,放进ArrList里,以现在手机的处理能力,要是超过40个服务,估计已经卡死,所以不用考虑超过40个该怎么办 int servicesSize = runningServices.size(); for (int i = 0; i < servicesSize; i++)// 循环枚举对比 { if (runningServices.get(i).service.getClassName().toString() .equals(serviceName)) { return true; } } return false; } @Override public void onDeleted(Context context, int[] appWidgetIds) { Log.i(TAG, "onDeleted"); } @Override public void onEnabled(Context context) { Log.i(TAG, "onEnabled"); TwitterService.setWidgetStatus(true); } @Override public void onDisabled(Context context) { Log.i(TAG, "onDisabled"); TwitterService.setWidgetStatus(false); } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * AbstractTwitterListBaseLine用于抽象tweets List的展现 * UI基本元素要求:一个ListView用于tweet列表 * 一个ProgressText用于提示信息 */ package com.ch_linghu.fanfoudroid.ui.base; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.TextView; import com.ch_linghu.fanfoudroid.DmActivity; import com.ch_linghu.fanfoudroid.MentionActivity; import com.ch_linghu.fanfoudroid.ProfileActivity; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.StatusActivity; import com.ch_linghu.fanfoudroid.TwitterActivity; import com.ch_linghu.fanfoudroid.WriteActivity; import com.ch_linghu.fanfoudroid.WriteDmActivity; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.helper.Preferences; import com.ch_linghu.fanfoudroid.helper.Utils; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.task.TweetCommonTask; import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter; public abstract class TwitterListBaseActivity extends WithHeaderActivity implements Refreshable { static final String TAG = "TwitterListBaseActivity"; protected TextView mProgressText; protected static final int STATE_ALL = 0; protected static final String SIS_RUNNING_KEY = "running"; // Tasks. protected GenericTask mFavTask; private TaskListener mFavTaskListener = new TaskAdapter(){ @Override public String getName() { return "FavoriteTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { onFavSuccess(); } else if (result == TaskResult.IO_ERROR) { onFavFailure(); } } }; static final int DIALOG_WRITE_ID = 0; abstract protected int getLayoutId(); abstract protected ListView getTweetList(); abstract protected TweetAdapter getTweetAdapter(); abstract protected void setupState(); abstract protected String getActivityTitle(); abstract protected boolean useBasicMenu(); abstract protected Tweet getContextItemTweet(int position); abstract protected void updateTweet(Tweet tweet); public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1; // public static final int CONTEXT_AT_ID = Menu.FIRST + 2; public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3; public static final int CONTEXT_DM_ID = Menu.FIRST + 4; public static final int CONTEXT_MORE_ID = Menu.FIRST + 5; public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6; public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7; /** * 如果增加了Context Menu常量的数量,则必须重载此方法, * 以保证其他人使用常量时不产生重复 * @return 最大的Context Menu常量 */ protected int getLastContextMenuId(){ return CONTEXT_DEL_FAV_ID; } @Override protected boolean _onCreate(Bundle savedInstanceState){ if (super._onCreate(savedInstanceState)){ setContentView(getLayoutId()); initHeader(HEADER_STYLE_HOME); mPreferences.getInt(Preferences.TWITTER_ACTIVITY_STATE_KEY, STATE_ALL); // 提示栏 mProgressText = (TextView) findViewById(R.id.progress_text); setupState(); registerForContextMenu(getTweetList()); registerOnClickListener(getTweetList()); return true; } else { return false; } } @Override protected void onResume() { super.onResume(); checkIsLogedIn(); } @Override protected void onDestroy() { super.onDestroy(); if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { mFavTask.cancel(true); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); if (useBasicMenu()){ AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; Tweet tweet = getContextItemTweet(info.position); if (tweet == null) { Log.w(TAG, "Selected item not available."); return; } menu.add(0, CONTEXT_MORE_ID, 0, tweet.screenName + getResources().getString(R.string.cmenu_user_profile_prefix)); menu.add(0, CONTEXT_REPLY_ID, 0, R.string.cmenu_reply); menu.add(0, CONTEXT_RETWEET_ID, 0, R.string.cmenu_retweet); menu.add(0, CONTEXT_DM_ID, 0, R.string.cmenu_direct_message); if (tweet.favorited.equals("true")) { menu.add(0, CONTEXT_DEL_FAV_ID, 0, R.string.cmenu_del_fav); } else { menu.add(0, CONTEXT_ADD_FAV_ID, 0, R.string.cmenu_add_fav); } } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); Tweet tweet = getContextItemTweet(info.position); if (tweet == null) { Log.w(TAG, "Selected item not available."); return super.onContextItemSelected(item); } switch (item.getItemId()) { case CONTEXT_MORE_ID: launchActivity(ProfileActivity.createIntent(tweet.userId)); return true; case CONTEXT_REPLY_ID: { // TODO: this isn't quite perfect. It leaves extra empty spaces if // you perform the reply action again. Intent intent = WriteActivity.createNewReplyIntent(tweet.screenName, tweet.id); startActivity(intent); return true; } case CONTEXT_RETWEET_ID: Intent intent = WriteActivity.createNewRepostIntent(this, tweet.text, tweet.screenName, tweet.id); startActivity(intent); return true; case CONTEXT_DM_ID: launchActivity(WriteDmActivity.createIntent(tweet.userId)); return true; case CONTEXT_ADD_FAV_ID: doFavorite("add", tweet.id); return true; case CONTEXT_DEL_FAV_ID: doFavorite("del", tweet.id); return true; default: return super.onContextItemSelected(item); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case OPTIONS_MENU_ID_TWEETS: launchActivity(TwitterActivity.createIntent(this)); return true; case OPTIONS_MENU_ID_REPLIES: launchActivity(MentionActivity.createIntent(this)); return true; case OPTIONS_MENU_ID_DM: launchActivity(DmActivity.createIntent()); return true; } return super.onOptionsItemSelected(item); } private void draw() { getTweetAdapter().refresh(); } private void goTop() { getTweetList().setSelection(1); } protected void adapterRefresh(){ getTweetAdapter().refresh(); } // for HasFavorite interface public void doFavorite(String action, String id) { if (!Utils.isEmpty(id)) { if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING){ return; }else{ mFavTask = new TweetCommonTask.FavoriteTask(this); mFavTask.setListener(mFavTaskListener); TaskParams params = new TaskParams(); params.put("action", action); params.put("id", id); mFavTask.execute(params); } } } public void onFavSuccess() { // updateProgress(getString(R.string.refreshing)); adapterRefresh(); } public void onFavFailure() { // updateProgress(getString(R.string.refreshing)); } protected void registerOnClickListener(ListView listView) { listView.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Tweet tweet = getContextItemTweet(position); if (tweet == null) { Log.w(TAG, "Selected item not available."); }else{ launchActivity(StatusActivity.createIntent(tweet)); } } }); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } }
Java
package com.ch_linghu.fanfoudroid.ui.base; import java.io.File; import android.app.Activity; import android.app.SearchManager; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.provider.MediaStore.MediaColumns; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.Window; import com.ch_linghu.fanfoudroid.AboutDialog; import com.ch_linghu.fanfoudroid.LoginActivity; import com.ch_linghu.fanfoudroid.PreferencesActivity; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterActivity; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.WriteActivity; import com.ch_linghu.fanfoudroid.data.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.helper.ImageManager; import com.ch_linghu.fanfoudroid.helper.Preferences; import com.ch_linghu.fanfoudroid.service.TwitterService; import com.ch_linghu.fanfoudroid.weibo.Weibo; /** * A BaseActivity has common routines and variables for an Activity * that contains a list of tweets and a text input field. * * Not the cleanest design, but works okay for several Activities in this app. */ public class BaseActivity extends Activity { private static final String TAG = "BaseActivity"; protected SharedPreferences mPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); _onCreate(savedInstanceState); } //因为onCreate方法无法返回状态,因此无法进行状态判断, //为了能对上层返回的信息进行判断处理,我们使用_onCreate代替真正的 //onCreate进行工作。onCreate仅在顶层调用_onCreate。 protected boolean _onCreate(Bundle savedInstanceState){ if (!checkIsLogedIn()){ return false; } else { //PreferenceManager.setDefaultValues(this, R.xml.preferences, false); mPreferences = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(this); manageUpdateChecks(); // No Titlebar requestWindowFeature(Window.FEATURE_NO_TITLE); requestWindowFeature(Window.FEATURE_PROGRESS); return true; } } protected void handleLoggedOut() { if (isTaskRoot()) { showLogin(); } else { setResult(RESULT_LOGOUT); } finish(); } public TwitterDatabase getDb() { return TwitterApplication.mDb; } public Weibo getApi() { return TwitterApplication.mApi; } public SharedPreferences getPreferences() { return mPreferences; } @Override protected void onDestroy() { super.onDestroy(); } protected boolean isLoggedIn() { return getApi().isLoggedIn(); } private static final int RESULT_LOGOUT = RESULT_FIRST_USER + 1; // Retrieve interface // public ImageManager getImageManager() { // return TwitterApplication.mImageManager; // } public void logout() { TwitterService.unschedule(this); getDb().clearData(); getApi().reset(); // Clear SharedPreferences SharedPreferences.Editor editor = mPreferences.edit(); editor.clear(); editor.commit(); TwitterApplication.mProfileImageCacheManager .getImageManager().clear(); // TODO: cancel notifications. TwitterService.unschedule(this); handleLoggedOut(); } protected void showLogin() { Intent intent = new Intent(this, LoginActivity.class); // TODO: might be a hack? intent.putExtra(Intent.EXTRA_INTENT, getIntent()); startActivity(intent); } protected void manageUpdateChecks() { boolean isEnabled = mPreferences.getBoolean( Preferences.CHECK_UPDATES_KEY, false); if (isEnabled) { TwitterService.schedule(this); } else if (!TwitterService.isWidgetEnabled()){ TwitterService.unschedule(this); } } // Menus. protected static final int OPTIONS_MENU_ID_LOGOUT = 1; protected static final int OPTIONS_MENU_ID_PREFERENCES = 2; protected static final int OPTIONS_MENU_ID_ABOUT = 3; protected static final int OPTIONS_MENU_ID_SEARCH = 4; protected static final int OPTIONS_MENU_ID_REPLIES = 5; protected static final int OPTIONS_MENU_ID_DM = 6; protected static final int OPTIONS_MENU_ID_TWEETS = 7; protected static final int OPTIONS_MENU_ID_TOGGLE_REPLIES = 8; protected static final int OPTIONS_MENU_ID_FOLLOW = 9; protected static final int OPTIONS_MENU_ID_UNFOLLOW = 10; protected static final int OPTIONS_MENU_ID_IMAGE_CAPTURE = 11; protected static final int OPTIONS_MENU_ID_PHOTO_LIBRARY = 12; protected static final int OPTIONS_MENU_ID_EXIT = 13; /** * 如果增加了Option Menu常量的数量,则必须重载此方法, * 以保证其他人使用常量时不产生重复 * @return 最大的Option Menu常量 */ protected int getLastOptionMenuId(){ return OPTIONS_MENU_ID_EXIT; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); // SubMenu submenu = menu.addSubMenu(R.string.write_label_insert_picture); // submenu.setIcon(android.R.drawable.ic_menu_gallery); // // submenu.add(0, OPTIONS_MENU_ID_IMAGE_CAPTURE, 0, R.string.write_label_take_a_picture); // submenu.add(0, OPTIONS_MENU_ID_PHOTO_LIBRARY, 0, R.string.write_label_choose_a_picture); // // MenuItem item = menu.add(0, OPTIONS_MENU_ID_SEARCH, 0, R.string.omenu_search); // item.setIcon(android.R.drawable.ic_search_category_default); // item.setAlphabeticShortcut(SearchManager.MENU_KEY); MenuItem item; item = menu.add(0, OPTIONS_MENU_ID_PREFERENCES, 0, R.string.omenu_settings); item.setIcon(android.R.drawable.ic_menu_preferences); item = menu.add(0, OPTIONS_MENU_ID_LOGOUT, 0, R.string.omenu_signout); item.setIcon(android.R.drawable.ic_menu_revert); item = menu.add(0, OPTIONS_MENU_ID_ABOUT, 0, R.string.omenu_about); item.setIcon(android.R.drawable.ic_menu_info_details); item = menu.add(0, OPTIONS_MENU_ID_EXIT, 0, R.string.omenu_exit); item.setIcon(android.R.drawable.ic_menu_rotate); return true; } protected static final int REQUEST_CODE_LAUNCH_ACTIVITY = 0; protected static final int REQUEST_CODE_PREFERENCES = 1; @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case OPTIONS_MENU_ID_LOGOUT: logout(); return true; case OPTIONS_MENU_ID_SEARCH: onSearchRequested(); return true; case OPTIONS_MENU_ID_PREFERENCES: Intent launchPreferencesIntent = new Intent().setClass(this, PreferencesActivity.class); startActivityForResult(launchPreferencesIntent, REQUEST_CODE_PREFERENCES); return true; case OPTIONS_MENU_ID_ABOUT: AboutDialog.show(this); return true; case OPTIONS_MENU_ID_EXIT: exit(); return true; } return super.onOptionsItemSelected(item); } protected void exit() { TwitterService.unschedule(this); Intent i = new Intent(Intent.ACTION_MAIN); i.addCategory(Intent.CATEGORY_HOME); startActivity(i); } protected void launchActivity(Intent intent) { // TODO: probably don't need this result chaining to finish upon logout. // since the subclasses have to check in onResume. startActivityForResult(intent, REQUEST_CODE_LAUNCH_ACTIVITY); } protected void launchDefaultActivity() { Intent intent = new Intent(); intent.setClass(this, TwitterActivity.class); startActivity(intent); } private String getRealPathFromURI(Uri contentUri) { String[] proj = { MediaColumns.DATA }; Cursor cursor = managedQuery(contentUri, proj, null, null, null); int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_PREFERENCES && resultCode == RESULT_OK) { manageUpdateChecks(); } else if (requestCode == REQUEST_CODE_LAUNCH_ACTIVITY && resultCode == RESULT_LOGOUT) { Log.i(TAG, "Result logout."); handleLoggedOut(); } } protected boolean checkIsLogedIn() { if (!getApi().isLoggedIn()) { Log.i(TAG, "Not logged in."); handleLoggedOut(); return false; } return true; } }
Java
package com.ch_linghu.fanfoudroid.ui.base; public interface Refreshable { void doRetrieve(); }
Java
package com.ch_linghu.fanfoudroid.ui.base; import android.app.Activity; import android.content.Intent; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.text.TextPaint; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.RelativeLayout.LayoutParams; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.SearchActivity; import com.ch_linghu.fanfoudroid.TwitterActivity; import com.ch_linghu.fanfoudroid.WriteActivity; import com.ch_linghu.fanfoudroid.ui.module.MenuDialog; public class WithHeaderActivity extends BaseActivity { private static final String TAG = "WithHeaderActivity"; public static final int HEADER_STYLE_HOME = 1; public static final int HEADER_STYLE_WRITE = 2; public static final int HEADER_STYLE_BACK = 3; public static final int HEADER_STYLE_SEARCH = 4; protected ImageButton refreshButton; protected ImageButton searchButton; protected ImageButton writeButton; protected TextView titleButton; protected Button backButton; protected ImageButton homeButton; protected MenuDialog dialog; protected EditText searchEdit; //搜索硬按键行为 @Override public boolean onSearchRequested() { Intent intent = new Intent(); intent.setClass(this, SearchActivity.class); startActivity(intent); return true; } // LOGO按钮 protected void addTitleButton() { // Find View titleButton = (TextView) findViewById(R.id.title); titleButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { int top = titleButton.getTop(); int height = titleButton.getHeight(); int x = top + height; if (null == dialog) { Log.i(TAG, "Create menu dialog."); dialog = new MenuDialog(WithHeaderActivity.this); dialog.bindEvent(WithHeaderActivity.this); dialog.setPosition(-1, x); } // toggle dialog if (dialog.isShowing()) { dialog.dismiss(); //没机会触发 } else { dialog.show(); } } }); } protected void setHeaderTitle(String title) { titleButton.setBackgroundDrawable( new BitmapDrawable()); titleButton.setText(title); LayoutParams lp = new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT,android.view.ViewGroup.LayoutParams.WRAP_CONTENT); lp.setMargins(3, 12, 0, 0); titleButton.setLayoutParams(lp); // 中文粗体 TextPaint tp = titleButton.getPaint(); tp.setFakeBoldText(true); } protected void setHeaderTitle(int resource) { titleButton.setBackgroundResource(resource); } // 刷新 protected void addRefreshButton() { final Activity that = this; refreshButton = (ImageButton) findViewById(R.id.top_refresh); refreshButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // 旋转动画 animRotate(v); if (that instanceof Refreshable) { ((Refreshable) that).doRetrieve(); } else { Log.e(TAG, "The current view " + that.getClass().getName() + " cann't be retrieved"); } } }); } protected void animRotate(View v) { if (null != v) { Animation anim = AnimationUtils.loadAnimation(v.getContext(), R.anim.rotate360); v.startAnimation(anim); } } // 搜索 protected void addSearchButton() { searchButton = (ImageButton) findViewById(R.id.search); searchButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // // 旋转动画 // Animation anim = AnimationUtils.loadAnimation(v.getContext(), // R.anim.scale_lite); // v.startAnimation(anim); //go to SearchActivity startSearch(); } }); } // 这个方法会在SearchActivity里重写 protected boolean startSearch() { Intent intent = new Intent(); intent.setClass(this, SearchActivity.class); startActivity(intent); return true; } //搜索框 protected void addSearchBox() { searchEdit = (EditText) findViewById(R.id.search_edit); } // 撰写 protected void addWriteButton() { writeButton = (ImageButton) findViewById(R.id.writeMessage); writeButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // 动画 Animation anim = AnimationUtils.loadAnimation(v.getContext(), R.anim.scale_lite); v.startAnimation(anim); // forward to write activity Intent intent = new Intent(); intent.setClass(v.getContext(), WriteActivity.class); v.getContext().startActivity(intent); } }); } // 回首页 protected void addHomeButton() { homeButton = (ImageButton) findViewById(R.id.home); homeButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // 动画 Animation anim = AnimationUtils.loadAnimation(v.getContext(), R.anim.scale_lite); v.startAnimation(anim); // forward to TwitterActivity Intent intent = new Intent(); intent.setClass(v.getContext(), TwitterActivity.class); v.getContext().startActivity(intent); } }); } // 返回 protected void addBackButton() { backButton = (Button) findViewById(R.id.top_back); // 中文粗体 // TextPaint tp = backButton.getPaint(); // tp.setFakeBoldText(true); backButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Go back to previous activity finish(); } }); } protected void initHeader(int style) { switch (style) { case HEADER_STYLE_HOME: addHeaderView(R.layout.header); addTitleButton(); addWriteButton(); addSearchButton(); addRefreshButton(); break; case HEADER_STYLE_BACK: addHeaderView(R.layout.header_back); addBackButton(); addWriteButton(); addSearchButton(); addRefreshButton(); break; case HEADER_STYLE_WRITE: addHeaderView(R.layout.header_write); addBackButton(); addSearchButton(); addHomeButton(); break; case HEADER_STYLE_SEARCH: addHeaderView(R.layout.header_search); addBackButton(); addSearchBox(); addSearchButton(); break; } } private void addHeaderView(int resource) { // find content root view ViewGroup root = (ViewGroup) getWindow().getDecorView(); ViewGroup content = (ViewGroup) root.getChildAt(0); View header = View.inflate(WithHeaderActivity.this, resource, null); // LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT); content.addView(header, 0); } @Override protected void onDestroy() { // dismiss dialog before destroy // to avoid android.view.WindowLeaked Exception if (dialog != null){ dialog.dismiss(); } super.onDestroy(); } }
Java
package com.ch_linghu.fanfoudroid.ui.base; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageButton; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.data.User; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskManager; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter; import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter; import com.ch_linghu.fanfoudroid.weibo.Paging; public abstract class UserArrayBaseActivity extends UserListBaseActivity { static final String TAG = "UserArrayBaseActivity"; // Views. protected ListView mUserList; protected UserArrayAdapter mUserListAdapter; protected TextView loadMoreBtn; protected ProgressBar loadMoreGIF; protected TextView loadMoreBtnTop; protected ProgressBar loadMoreGIFTop; protected static int lastPosition = 0; // Tasks. protected TaskManager taskManager = new TaskManager(); private GenericTask mRetrieveTask; private GenericTask mFollowersRetrieveTask; private GenericTask mGetMoreTask;// 每次100用户 public abstract Paging getCurrentPage();// 加载 public abstract Paging getNextPage();// 加载 //protected abstract String[] getIds(); protected abstract List<com.ch_linghu.fanfoudroid.weibo.User> getUsers(String userId,Paging page) throws HttpException; private ArrayList<com.ch_linghu.fanfoudroid.data.User> allUserList; @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.i(TAG, "onCreate."); if (super._onCreate(savedInstanceState)) { doRetrieve();//加载第一页 return true; } else { return false; } } @Override public void doRetrieve() { Log.i(TAG, "Attempting retrieve."); // 旋转刷新按钮 animRotate(refreshButton); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING){ return; }else{ mRetrieveTask = new RetrieveTask(); mRetrieveTask.setListener(mRetrieveTaskListener); mRetrieveTask.execute(); // Add Task to manager taskManager.addTask(mRetrieveTask); } } private TaskListener mRetrieveTaskListener = new TaskAdapter(){ @Override public String getName() { return "RetrieveTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { draw(); } // 刷新按钮停止旋转 getRefreshButton().clearAnimation(); updateProgress(""); } @Override public void onPreExecute(GenericTask task) { onRetrieveBegin(); } @Override public void onProgressUpdate(GenericTask task, Object param) { Log.d(TAG, "onProgressUpdate"); draw(); } }; public void updateProgress(String progress) { mProgressText.setText(progress); } public void onRetrieveBegin() { updateProgress(getString(R.string.page_status_refreshing)); } /** * TODO:从API获取当前Followers * @author Dino * */ private class RetrieveTask extends GenericTask{ @Override protected TaskResult _doInBackground(TaskParams... params) { Log.i(TAG, "load RetrieveTask"); List<com.ch_linghu.fanfoudroid.weibo.User> usersList=null; try { usersList=getUsers(getUserId(),getCurrentPage()); } catch (HttpException e) { e.printStackTrace(); return TaskResult.IO_ERROR; } for (com.ch_linghu.fanfoudroid.weibo.User user : usersList) { if (isCancelled()) { return TaskResult.CANCELLED; } allUserList.add(User.create(user)); if (isCancelled()) { return TaskResult.CANCELLED; } } return TaskResult.OK; } } @Override protected int getLayoutId() { return R.layout.follower; } @Override protected void setupState() { setTitle(getActivityTitle()); mUserList = (ListView) findViewById(R.id.follower_list); setupListHeader(true); mUserListAdapter = new UserArrayAdapter(this); mUserList.setAdapter(mUserListAdapter); allUserList=new ArrayList<com.ch_linghu.fanfoudroid.data.User>(); } @Override protected String getActivityTitle() { // TODO Auto-generated method stub return null; } @Override protected boolean useBasicMenu() { return true; } @Override protected User getContextItemUser(int position) { // position = position - 1; // 加入footer跳过footer if (position < mUserListAdapter.getCount()) { User item = (User)mUserListAdapter.getItem(position); if (item == null) { return null; } else { return item; } } else { return null; } } /** * TODO:不知道啥用 */ @Override protected void updateTweet(Tweet tweet) { // TODO Auto-generated method stub } @Override protected ListView getUserList() { return mUserList; } @Override protected TweetAdapter getUserAdapter() { return mUserListAdapter; } /** * 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用 */ protected void setupListHeader(boolean addFooter) { // TODO: 完成listView底部的事件绑定 View footer = View.inflate(this, R.layout.listview_footer, null); // TextView footerText=(TextView) // footer.findViewById(R.id.ask_for_more); mUserList.addFooterView(footer, null, true); footer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loadMoreGIF.setVisibility(View.VISIBLE); doGetMore(); } }); // Find View loadMoreBtn = (TextView) findViewById(R.id.ask_for_more); loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar); } public void doGetMore() { Log.i(TAG, "Attempting getMore."); // 旋转刷新按钮 animRotate(refreshButton); if (mGetMoreTask != null && mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mGetMoreTask = new GetMoreTask(); mGetMoreTask.setListener(getMoreListener); mGetMoreTask.execute(); // Add Task to manager taskManager.addTask(mGetMoreTask); } } private TaskListener getMoreListener = new TaskAdapter() { @Override public String getName() { return "getMore"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { super.onPostExecute(task, result); draw(); getRefreshButton().clearAnimation(); loadMoreGIF.setVisibility(View.GONE); } }; /** * TODO:需要重写,获取下一批用户,按页分100页一次 * * @author Dino * */ private class GetMoreTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { Log.i(TAG, "load RetrieveTask"); List<com.ch_linghu.fanfoudroid.weibo.User> usersList = null; try { usersList = getUsers(getUserId(), getNextPage()); } catch (HttpException e) { e.printStackTrace(); return TaskResult.IO_ERROR; } //将获取到的数据(保存/更新)到数据库 getDb().syncWeiboUsers(usersList); for (com.ch_linghu.fanfoudroid.weibo.User user : usersList) { if (isCancelled()) { return TaskResult.CANCELLED; } allUserList.add(User.create(user)); if (isCancelled()) { return TaskResult.CANCELLED; } } return TaskResult.OK; } } public void draw() { mUserListAdapter.refresh(allUserList); } public ImageButton getRefreshButton() { return refreshButton; } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid.ui.base; import java.util.ArrayList; import java.util.List; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.ImageButton; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.data.User; import com.ch_linghu.fanfoudroid.data.db.UserInfoTable; import com.ch_linghu.fanfoudroid.helper.Preferences; import com.ch_linghu.fanfoudroid.helper.Utils; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskManager; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter; import com.ch_linghu.fanfoudroid.ui.module.UserCursorAdapter; import com.ch_linghu.fanfoudroid.weibo.Paging; import com.ch_linghu.fanfoudroid.weibo.Status; /** * TwitterCursorBaseLine用于带有静态数据来源(对应数据库的,与twitter表同构的特定表)的展现 */ public abstract class UserCursorBaseActivity extends UserListBaseActivity{ /** * 第一种方案:(采取第一种) * 暂不放在数据库中,直接从Api读取。 * * 第二种方案: * 麻烦的是api数据与数据库同步,当收听人数比较多的时候,一次性读取太费流量 * 按照饭否api每次分页100人 * 当收听数<100时先从数据库一次性根据API返回的ID列表读取数据,如果数据库中的收听数<总数,那么从API中读取所有用户信息并同步到数据库中。 * 当收听数>100时采取分页加载,先按照id 获取数据库里前100用户,如果用户数量<100则从api中加载,从page=1开始下载,同步到数据库中,单击更多继续从数据库中加载 * 当数据库中的数据读取到最后一页后,则从api中加载并更新到数据库中。 * 单击刷新按钮则从api加载并同步到数据库中 * */ static final String TAG = "UserCursorBaseActivity"; // Views. protected ListView mUserList; protected UserCursorAdapter mUserListAdapter; protected TextView loadMoreBtn; protected ProgressBar loadMoreGIF; protected TextView loadMoreBtnTop; protected ProgressBar loadMoreGIFTop; protected static int lastPosition = 0; // Tasks. protected TaskManager taskManager = new TaskManager(); private GenericTask mRetrieveTask; private GenericTask mFollowersRetrieveTask; private GenericTask mGetMoreTask;//每次十个用户 protected abstract String getUserId();//获得用户id private TaskListener mRetrieveTaskListener = new TaskAdapter(){ @Override public String getName() { return "RetrieveTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { SharedPreferences.Editor editor = getPreferences().edit(); editor.putLong(Preferences.LAST_TWEET_REFRESH_KEY, Utils .getNowTime()); editor.commit(); //TODO: 1. StatusType(DONE) ; 2. 只有在取回的数据大于MAX时才做GC, 因为小于时可以保证数据的连续性 //FIXME: gc需要带owner //getDb().gc(getDatabaseType()); // GC draw(); goTop(); } else { // Do nothing. } // 刷新按钮停止旋转 getRefreshButton().clearAnimation(); //loadMoreGIFTop.setVisibility(View.GONE); updateProgress(""); } @Override public void onPreExecute(GenericTask task) { onRetrieveBegin(); } @Override public void onProgressUpdate(GenericTask task, Object param) { Log.d(TAG, "onProgressUpdate"); draw(); } }; private TaskListener mFollowerRetrieveTaskListener = new TaskAdapter(){ @Override public String getName() { return "FollowerRetrieve"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { SharedPreferences sp = getPreferences(); SharedPreferences.Editor editor = sp.edit(); editor.putLong(Preferences.LAST_FOLLOWERS_REFRESH_KEY, Utils.getNowTime()); editor.commit(); } else { // Do nothing. } } }; // Refresh data at startup if last refresh was this long ago or greater. private static final long REFRESH_THRESHOLD = 5 * 60 * 1000; // Refresh followers if last refresh was this long ago or greater. private static final long FOLLOWERS_REFRESH_THRESHOLD = 12 * 60 * 60 * 1000; abstract protected Cursor fetchUsers(); public abstract int getDatabaseType(); public abstract String fetchMaxId(); public abstract String fetchMinId(); public abstract List<com.ch_linghu.fanfoudroid.weibo.User> getUsers() throws HttpException; public abstract void addUsers(ArrayList<com.ch_linghu.fanfoudroid.data.User> tusers); // public abstract List<Status> getMessageSinceId(String maxId) // throws WeiboException; public abstract List<com.ch_linghu.fanfoudroid.weibo.User> getUserSinceId(String maxId) throws HttpException; public abstract List<Status> getMoreMessageFromId(String minId) throws HttpException; public abstract Paging getNextPage();//下一页数 public abstract Paging getCurrentPage();//当前页数 protected abstract String[] getIds(); public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1; // public static final int CONTEXT_AT_ID = Menu.FIRST + 2; public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3; public static final int CONTEXT_DM_ID = Menu.FIRST + 4; public static final int CONTEXT_MORE_ID = Menu.FIRST + 5; public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6; public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7; @Override protected void setupState() { Cursor cursor; cursor = fetchUsers(); // setTitle(getActivityTitle()); startManagingCursor(cursor); mUserList = (ListView) findViewById(R.id.follower_list); //TODO: 需处理没有数据时的情况 Log.i("LDS", cursor.getCount()+" cursor count"); setupListHeader(true); mUserListAdapter = new UserCursorAdapter(this, cursor); mUserList.setAdapter(mUserListAdapter); //? registerOnClickListener(mTweetList); } /** * 绑定listView底部 - 载入更多 * NOTE: 必须在listView#setAdapter之前调用 */ protected void setupListHeader(boolean addFooter) { //TODO: 完成listView底部的事件绑定 View footer = View.inflate(this, R.layout.listview_footer, null); // TextView footerText=(TextView) footer.findViewById(R.id.ask_for_more); mUserList.addFooterView(footer, null, true); footer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loadMoreGIF.setVisibility(View.VISIBLE); doGetMore(); } }); // Find View loadMoreBtn = (TextView)findViewById(R.id.ask_for_more); loadMoreGIF = (ProgressBar)findViewById(R.id.rectangleProgressBar); //loadMoreBtnTop = (TextView)findViewById(R.id.ask_for_more_header); //loadMoreGIFTop = (ProgressBar)findViewById(R.id.rectangleProgressBar_header); //loadMoreAnimation = (AnimationDrawable) loadMoreGIF.getIndeterminateDrawable(); } @Override protected int getLayoutId(){ return R.layout.follower; } @Override protected ListView getUserList() { return mUserList; } @Override protected TweetAdapter getUserAdapter() { return mUserListAdapter; } @Override protected boolean useBasicMenu(){ return true; } protected User getContextItemUser(int position){ //position = position - 1; //加入footer跳过footer if (position < mUserListAdapter.getCount()){ Cursor cursor = (Cursor) mUserListAdapter.getItem(position); if (cursor == null){ return null; }else{ return UserInfoTable.parseCursor(cursor); } }else{ return null; } } @Override protected void updateTweet(Tweet tweet){ // TODO: updateTweet() 在哪里调用的? 目前尚只支持: // updateTweet(String tweetId, ContentValues values) // setFavorited(String tweetId, String isFavorited) // 看是否还需要增加updateTweet(Tweet tweet)方法 //对所有相关表的对应消息都进行刷新(如果存在的话) // getDb().updateTweet(TwitterDbAdapter.TABLE_FAVORITE, tweet); // getDb().updateTweet(TwitterDbAdapter.TABLE_MENTION, tweet); // getDb().updateTweet(TwitterDbAdapter.TABLE_TWEET, tweet); } @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.i(TAG, "onCreate."); if (super._onCreate(savedInstanceState)){ goTop(); // skip the header boolean shouldRetrieve = false; //FIXME: 该子类页面全部使用了这个统一的计时器,导致进入Mention等分页面后经常不会自动刷新 long lastRefreshTime = mPreferences.getLong( Preferences.LAST_TWEET_REFRESH_KEY, 0); long nowTime = Utils.getNowTime(); long diff = nowTime - lastRefreshTime; Log.i(TAG, "Last refresh was " + diff + " ms ago."); /* if (diff > REFRESH_THRESHOLD) { shouldRetrieve = true; } else if (Utils.isTrue(savedInstanceState, SIS_RUNNING_KEY)) { // Check to see if it was running a send or retrieve task. // It makes no sense to resend the send request (don't want dupes) // so we instead retrieve (refresh) to see if the message has // posted. Log.i(TAG, "Was last running a retrieve or send task. Let's refresh."); shouldRetrieve = true; } */ shouldRetrieve=true; if (shouldRetrieve) { doRetrieve(); } long lastFollowersRefreshTime = mPreferences.getLong( Preferences.LAST_FOLLOWERS_REFRESH_KEY, 0); diff = nowTime - lastFollowersRefreshTime; Log.i(TAG, "Last followers refresh was " + diff + " ms ago."); /* if (diff > FOLLOWERS_REFRESH_THRESHOLD && (mRetrieveTask == null || mRetrieveTask.getStatus() != GenericTask.Status.RUNNING)) { Log.i(TAG, "Refresh followers."); doRetrieveFollowers(); } */ return true; }else{ return false; } } @Override protected void onResume() { Log.i(TAG, "onResume."); if (lastPosition != 0) { mUserList.setSelection(lastPosition); } super.onResume(); checkIsLogedIn(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } @Override protected void onRestoreInstanceState(Bundle bundle) { super.onRestoreInstanceState(bundle); // mTweetEdit.updateCharsRemain(); } @Override protected void onDestroy() { Log.i(TAG, "onDestroy."); super.onDestroy(); taskManager.cancelAll(); } @Override protected void onPause() { Log.i(TAG, "onPause."); super.onPause(); lastPosition = mUserList.getFirstVisiblePosition(); } @Override protected void onRestart() { Log.i(TAG, "onRestart."); super.onRestart(); } @Override protected void onStart() { Log.i(TAG, "onStart."); super.onStart(); } @Override protected void onStop() { Log.i(TAG, "onStop."); super.onStop(); } // UI helpers. @Override protected String getActivityTitle() { // TODO Auto-generated method stub return null; } @Override protected void adapterRefresh() { mUserListAdapter.notifyDataSetChanged(); mUserListAdapter.refresh(); } // Retrieve interface public void updateProgress(String progress) { mProgressText.setText(progress); } public void draw() { mUserListAdapter.refresh(); } public void goTop() { Log.i(TAG, "goTop."); mUserList.setSelection(1); } private void doRetrieveFollowers() { Log.i(TAG, "Attempting followers retrieve."); if (mFollowersRetrieveTask != null && mFollowersRetrieveTask.getStatus() == GenericTask.Status.RUNNING){ return; }else{ mFollowersRetrieveTask = new FollowersRetrieveTask(); mFollowersRetrieveTask.setListener(mFollowerRetrieveTaskListener); mFollowersRetrieveTask.execute(); taskManager.addTask(mFollowersRetrieveTask); // Don't need to cancel FollowersTask (assuming it ends properly). mFollowersRetrieveTask.setCancelable(false); } } public void onRetrieveBegin() { updateProgress(getString(R.string.page_status_refreshing)); } public void doRetrieve() { Log.i(TAG, "Attempting retrieve."); // 旋转刷新按钮 animRotate(refreshButton); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING){ return; }else{ mRetrieveTask = new RetrieveTask(); mRetrieveTask.setListener(mRetrieveTaskListener); mRetrieveTask.execute(); // Add Task to manager taskManager.addTask(mRetrieveTask); } } // for Retrievable interface public ImageButton getRefreshButton() { return refreshButton; } /** * TODO:从API获取当前Followers,并同步到数据库 * @author Dino * */ private class RetrieveTask extends GenericTask{ @Override protected TaskResult _doInBackground(TaskParams... params) { Log.i(TAG, "load RetrieveTask"); List<com.ch_linghu.fanfoudroid.weibo.User> usersList=null; try { usersList=getApi().getFollowersList(getUserId(),getCurrentPage()); } catch (HttpException e) { e.printStackTrace(); } ArrayList<User> users=new ArrayList<User>(); for (com.ch_linghu.fanfoudroid.weibo.User user : usersList) { if (isCancelled()) { return TaskResult.CANCELLED; } users.add(User.create(user)); if (isCancelled()) { return TaskResult.CANCELLED; } } addUsers(users); return TaskResult.OK; } } private class FollowersRetrieveTask extends GenericTask{ @Override protected TaskResult _doInBackground(TaskParams... params) { try { Log.i(TAG, "load FollowersErtrieveTask"); List<com.ch_linghu.fanfoudroid.weibo.User> t_users= getUsers(); getDb().syncWeiboUsers(t_users); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } return TaskResult.OK; } } /** * TODO:需要重写,获取下一批用户,按页分100页一次 * @author Dino * */ private class GetMoreTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { Log.i(TAG, "load RetrieveTask"); List<com.ch_linghu.fanfoudroid.weibo.User> usersList=null; try { usersList=getApi().getFollowersList(getUserId(),getNextPage()); } catch (HttpException e) { e.printStackTrace(); } ArrayList<User> users=new ArrayList<User>(); for (com.ch_linghu.fanfoudroid.weibo.User user : usersList) { if (isCancelled()) { return TaskResult.CANCELLED; } users.add(User.create(user)); if (isCancelled()) { return TaskResult.CANCELLED; } } addUsers(users); return TaskResult.OK; } } private TaskListener getMoreListener = new TaskAdapter() { @Override public String getName() { return "getMore"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { super.onPostExecute(task, result); draw(); getRefreshButton().clearAnimation(); loadMoreGIF.setVisibility(View.GONE); } }; public void doGetMore() { Log.i(TAG, "Attempting getMore."); // 旋转刷新按钮 animRotate(refreshButton); if (mGetMoreTask != null && mGetMoreTask.getStatus() == GenericTask.Status.RUNNING){ return; }else{ mGetMoreTask = new GetMoreTask(); mGetMoreTask.setListener(getMoreListener); mGetMoreTask.execute(); // Add Task to manager taskManager.addTask(mGetMoreTask); } } }
Java
package com.ch_linghu.fanfoudroid.ui.base; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.ch_linghu.fanfoudroid.DmActivity; import com.ch_linghu.fanfoudroid.MentionActivity; import com.ch_linghu.fanfoudroid.ProfileActivity; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterActivity; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.UserTimelineActivity; import com.ch_linghu.fanfoudroid.WriteActivity; import com.ch_linghu.fanfoudroid.WriteDmActivity; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.data.User; import com.ch_linghu.fanfoudroid.helper.Preferences; import com.ch_linghu.fanfoudroid.helper.Utils; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.task.TweetCommonTask; import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter; public abstract class UserListBaseActivity extends WithHeaderActivity implements Refreshable { static final String TAG = "TwitterListBaseActivity"; protected TextView mProgressText; protected static final int STATE_ALL = 0; protected static final String SIS_RUNNING_KEY = "running"; private static final String USER_ID="userId"; // Tasks. protected GenericTask mFavTask; private TaskListener mFavTaskListener = new TaskAdapter(){ @Override public String getName() { return "FavoriteTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { onFavSuccess(); } else if (result == TaskResult.IO_ERROR) { onFavFailure(); } } }; static final int DIALOG_WRITE_ID = 0; abstract protected int getLayoutId(); abstract protected ListView getUserList(); abstract protected TweetAdapter getUserAdapter(); abstract protected void setupState(); abstract protected String getActivityTitle(); abstract protected boolean useBasicMenu(); abstract protected User getContextItemUser(int position); abstract protected void updateTweet(Tweet tweet); protected abstract String getUserId();// 获得用户id //public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1; //public static final int CONTEXT_AT_ID = Menu.FIRST + 2; //public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3; //public static final int CONTEXT_DM_ID = Menu.FIRST + 4; //public static final int CONTEXT_MORE_ID = Menu.FIRST + 5; //public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6; //public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7; public static final int CONTENT_PROFILE_ID=Menu.FIRST+1; //public static final int CONTENT_ADD_BLOCK_ID=Menu.FIRST+2; public static final int CONTENT_STATUS_ID=Menu.FIRST+2; public static final int CONTENT_DEL_FRIEND=Menu.FIRST+3; public static final int CONTENT_ADD_FRIEND=Menu.FIRST+4; public static final int CONTENT_SEND_DM=Menu.FIRST+5; public static final int CONTENT_SEND_MENTION=Menu.FIRST+6; /** * 如果增加了Context Menu常量的数量,则必须重载此方法, * 以保证其他人使用常量时不产生重复 * @return 最大的Context Menu常量 */ //protected int getLastContextMenuId(){ // return CONTEXT_DEL_FAV_ID; //} @Override protected boolean _onCreate(Bundle savedInstanceState){ if (super._onCreate(savedInstanceState)){ setContentView(getLayoutId()); String myself = TwitterApplication.getMyselfId(); if(getUserId()==myself){ initHeader(HEADER_STYLE_HOME); }else{ initHeader(HEADER_STYLE_BACK); } mPreferences.getInt(Preferences.TWITTER_ACTIVITY_STATE_KEY, STATE_ALL); // 提示栏 mProgressText = (TextView) findViewById(R.id.progress_text); setupState(); registerForContextMenu(getUserList()); registerOnClickListener(getUserList()); return true; } else { return false; } } @Override protected void onResume() { super.onResume(); checkIsLogedIn(); } @Override protected void onDestroy() { super.onDestroy(); if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { mFavTask.cancel(true); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); if (useBasicMenu()){ AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; User user = getContextItemUser(info.position); if (user == null) { Log.w(TAG, "Selected item not available."); return ; } menu.add(0, CONTENT_PROFILE_ID, 0, user.screenName + getResources().getString(R.string.cmenu_user_profile_prefix)); menu.add(0,CONTENT_STATUS_ID,0,user.screenName+getResources().getString(R.string.cmenu_user_status)); menu.add(0,CONTENT_SEND_MENTION,0,getResources().getString(R.string.cmenu_user_send_prefix)+user.screenName+getResources().getString(R.string.cmenu_user_sendmention_suffix)); menu.add(0,CONTENT_SEND_DM,0,getResources().getString(R.string.cmenu_user_send_prefix)+user.screenName+getResources().getString(R.string.cmenu_user_senddm_suffix)); } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); User user = getContextItemUser(info.position); if (user == null) { Log.w(TAG, "Selected item not available."); return super.onContextItemSelected(item); } switch (item.getItemId()) { case CONTENT_PROFILE_ID: launchActivity(ProfileActivity.createIntent(user.id)); return true; case CONTENT_STATUS_ID: launchActivity(UserTimelineActivity.createIntent(user.id, user.name)); return true; case CONTENT_DEL_FRIEND: delFriend(user.id); return true; case CONTENT_ADD_FRIEND: addFriend(user.id); return true; case CONTENT_SEND_MENTION: launchActivity(WriteActivity.createNewTweetIntent( String.format("@%s ", user.screenName))); return true; case CONTENT_SEND_DM: launchActivity(WriteDmActivity.createIntent(user.id)); return true; default: return super.onContextItemSelected(item); } } /** * 取消关注 * @param id */ private void delFriend(final String id) { Builder diaBuilder = new AlertDialog.Builder(UserListBaseActivity.this) .setTitle("关注提示").setMessage("确实要取消关注吗?"); diaBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (cancelFollowingTask != null && cancelFollowingTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { cancelFollowingTask = new CancelFollowingTask(); cancelFollowingTask .setListener(cancelFollowingTaskLinstener); TaskParams params = new TaskParams(); params.put(USER_ID, id); cancelFollowingTask.execute(params); } } }); diaBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); Dialog dialog = diaBuilder.create(); dialog.show(); } private GenericTask cancelFollowingTask; /** * 取消关注 * * @author Dino * */ private class CancelFollowingTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { //TODO:userid String userId=params[0].getString(USER_ID); getApi().destroyFriendship(userId); } catch (HttpException e) { Log.w(TAG, "create friend ship error"); return TaskResult.FAILED; } return TaskResult.OK; } } private TaskListener cancelFollowingTaskLinstener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { // followingBtn.setText("添加关注"); // isFollowingText.setText(getResources().getString( // R.string.profile_notfollowing)); // followingBtn.setOnClickListener(setfollowingListener); Toast.makeText(getBaseContext(), "取消关注成功", Toast.LENGTH_SHORT).show(); } else if (result == TaskResult.FAILED) { Toast.makeText(getBaseContext(), "取消关注失败", Toast.LENGTH_SHORT).show(); } } @Override public String getName() { // TODO Auto-generated method stub return null; } }; private GenericTask setFollowingTask; /** * 设置关注 * @param id */ private void addFriend(String id){ Builder diaBuilder = new AlertDialog.Builder(UserListBaseActivity.this) .setTitle("关注提示").setMessage("确实要添加关注吗?"); diaBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (setFollowingTask != null && setFollowingTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { setFollowingTask = new SetFollowingTask(); setFollowingTask .setListener(setFollowingTaskLinstener); TaskParams params = new TaskParams(); setFollowingTask.execute(params); } } }); diaBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); Dialog dialog = diaBuilder.create(); dialog.show(); } /** * 设置关注 * * @author Dino * */ private class SetFollowingTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { String userId=params[0].getString(USER_ID); getApi().createFriendship(userId); } catch (HttpException e) { Log.w(TAG, "create friend ship error"); return TaskResult.FAILED; } return TaskResult.OK; } } private TaskListener setFollowingTaskLinstener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { // followingBtn.setText("取消关注"); // isFollowingText.setText(getResources().getString( // R.string.profile_isfollowing)); // followingBtn.setOnClickListener(cancelFollowingListener); Toast.makeText(getBaseContext(), "关注成功", Toast.LENGTH_SHORT).show(); } else if (result == TaskResult.FAILED) { Toast.makeText(getBaseContext(), "关注失败", Toast.LENGTH_SHORT).show(); } } @Override public String getName() { // TODO Auto-generated method stub return null; } }; @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case OPTIONS_MENU_ID_TWEETS: launchActivity(TwitterActivity.createIntent(this)); return true; case OPTIONS_MENU_ID_REPLIES: launchActivity(MentionActivity.createIntent(this)); return true; case OPTIONS_MENU_ID_DM: launchActivity(DmActivity.createIntent()); return true; } return super.onOptionsItemSelected(item); } private void draw() { getUserAdapter().refresh(); } private void goTop() { getUserList().setSelection(1); } protected void adapterRefresh(){ getUserAdapter().refresh(); } // for HasFavorite interface public void doFavorite(String action, String id) { if (!Utils.isEmpty(id)) { if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING){ return; }else{ mFavTask = new TweetCommonTask.FavoriteTask(this); mFavTask.setListener(mFavTaskListener); TaskParams params = new TaskParams(); params.put("action", action); params.put("id", id); mFavTask.execute(params); } } } public void onFavSuccess() { // updateProgress(getString(R.string.refreshing)); adapterRefresh(); } public void onFavFailure() { // updateProgress(getString(R.string.refreshing)); } /* * TODO:单击列表项 * * */ protected void registerOnClickListener(ListView listView) { listView.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //Toast.makeText(getBaseContext(), "选择第"+position+"个列表",Toast.LENGTH_SHORT).show(); User user=getContextItemUser(position); if(user==null){ Log.w(TAG, "selected item not available"); }else{ launchActivity(ProfileActivity.createIntent(user.id)); } } }); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid.ui.base; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.ImageButton; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.data.db.StatusTable; import com.ch_linghu.fanfoudroid.helper.Preferences; import com.ch_linghu.fanfoudroid.helper.Utils; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskManager; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter; import com.ch_linghu.fanfoudroid.ui.module.TweetCursorAdapter; import com.ch_linghu.fanfoudroid.weibo.IDs; import com.ch_linghu.fanfoudroid.weibo.Status; /** * TwitterCursorBaseLine用于带有静态数据来源(对应数据库的,与twitter表同构的特定表)的展现 */ public abstract class TwitterCursorBaseActivity extends TwitterListBaseActivity{ static final String TAG = "TwitterListBaseActivity"; // Views. protected ListView mTweetList; protected TweetCursorAdapter mTweetAdapter; protected View mListHeader; protected View mListFooter; protected TextView loadMoreBtn; protected ProgressBar loadMoreGIF; protected TextView loadMoreBtnTop; protected ProgressBar loadMoreGIFTop; protected static int lastPosition = 0; // Tasks. protected TaskManager taskManager = new TaskManager(); private GenericTask mRetrieveTask; private GenericTask mFollowersRetrieveTask; private GenericTask mGetMoreTask; private int mRetrieveCount = 0; private TaskListener mRetrieveTaskListener = new TaskAdapter(){ @Override public String getName() { return "RetrieveTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { SharedPreferences.Editor editor = getPreferences().edit(); editor.putLong(Preferences.LAST_TWEET_REFRESH_KEY, Utils .getNowTime()); editor.commit(); //TODO: 1. StatusType(DONE) ; if (mRetrieveCount >= StatusTable.MAX_ROW_NUM){ //只有在取回的数据大于MAX时才做GC, 因为小于时可以保证数据的连续性 getDb().gc(getUserId(), getDatabaseType()); // GC } draw(); goTop(); } else { // Do nothing. } // 刷新按钮停止旋转 getRefreshButton().clearAnimation(); loadMoreGIFTop.setVisibility(View.GONE); updateProgress(""); } @Override public void onPreExecute(GenericTask task) { onRetrieveBegin(); } @Override public void onProgressUpdate(GenericTask task, Object param) { Log.d(TAG, "onProgressUpdate"); draw(); } }; private TaskListener mFollowerRetrieveTaskListener = new TaskAdapter(){ @Override public String getName() { return "FollowerRetrieve"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { SharedPreferences sp = getPreferences(); SharedPreferences.Editor editor = sp.edit(); editor.putLong(Preferences.LAST_FOLLOWERS_REFRESH_KEY, Utils.getNowTime()); editor.commit(); } else { // Do nothing. } } }; // Refresh data at startup if last refresh was this long ago or greater. private static final long REFRESH_THRESHOLD = 5 * 60 * 1000; // Refresh followers if last refresh was this long ago or greater. private static final long FOLLOWERS_REFRESH_THRESHOLD = 12 * 60 * 60 * 1000; abstract protected void markAllRead(); abstract protected Cursor fetchMessages(); public abstract int getDatabaseType(); public abstract String getUserId(); public abstract String fetchMaxId(); public abstract String fetchMinId(); public abstract int addMessages(ArrayList<Tweet> tweets, boolean isUnread); public abstract List<Status> getMessageSinceId(String maxId) throws HttpException; public abstract List<Status> getMoreMessageFromId(String minId) throws HttpException; public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1; // public static final int CONTEXT_AT_ID = Menu.FIRST + 2; public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3; public static final int CONTEXT_DM_ID = Menu.FIRST + 4; public static final int CONTEXT_MORE_ID = Menu.FIRST + 5; public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6; public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7; @Override protected void setupState() { Cursor cursor; cursor = fetchMessages(); // getDb().fetchMentions(); setTitle(getActivityTitle()); startManagingCursor(cursor); mTweetList = (ListView) findViewById(R.id.tweet_list); //TODO: 需处理没有数据时的情况 Log.i("LDS", cursor.getCount()+" cursor count"); setupListHeader(true); mTweetAdapter = new TweetCursorAdapter(this, cursor); mTweetList.setAdapter(mTweetAdapter); //? registerOnClickListener(mTweetList); } /** * 绑定listView底部 - 载入更多 * NOTE: 必须在listView#setAdapter之前调用 */ protected void setupListHeader(boolean addFooter) { // Add Header to ListView mListHeader = View.inflate(this, R.layout.listview_header, null); mTweetList.addHeaderView(mListHeader, null, true); mListHeader.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loadMoreGIFTop.setVisibility(View.VISIBLE); doRetrieve(); } }); //TODO: 完成listView顶部和底部的事件绑定 mListFooter = View.inflate(this, R.layout.listview_footer, null); mTweetList.addFooterView(mListFooter, null, true); mListFooter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loadMoreGIF.setVisibility(View.VISIBLE); doGetMore(); } }); // Find View loadMoreBtn = (TextView)findViewById(R.id.ask_for_more); loadMoreGIF = (ProgressBar)findViewById(R.id.rectangleProgressBar); loadMoreBtnTop = (TextView)findViewById(R.id.ask_for_more_header); loadMoreGIFTop = (ProgressBar)findViewById(R.id.rectangleProgressBar_header); //loadMoreAnimation = (AnimationDrawable) loadMoreGIF.getIndeterminateDrawable(); } @Override protected int getLayoutId(){ return R.layout.main; } @Override protected ListView getTweetList(){ return mTweetList; } @Override protected TweetAdapter getTweetAdapter(){ return mTweetAdapter; } @Override protected boolean useBasicMenu(){ return true; } @Override protected Tweet getContextItemTweet(int position){ position = position - 1; //因为List加了Header和footer,所以要跳过第一个以及忽略最后一个 if (position >= 0 && position < mTweetAdapter.getCount()){ Cursor cursor = (Cursor) mTweetAdapter.getItem(position); if (cursor == null){ return null; }else{ return StatusTable.parseCursor(cursor); } }else{ return null; } } @Override protected void updateTweet(Tweet tweet){ // TODO: updateTweet() 在哪里调用的? 目前尚只支持: // updateTweet(String tweetId, ContentValues values) // setFavorited(String tweetId, String isFavorited) // 看是否还需要增加updateTweet(Tweet tweet)方法 //对所有相关表的对应消息都进行刷新(如果存在的话) // getDb().updateTweet(TwitterDbAdapter.TABLE_FAVORITE, tweet); // getDb().updateTweet(TwitterDbAdapter.TABLE_MENTION, tweet); // getDb().updateTweet(TwitterDbAdapter.TABLE_TWEET, tweet); } @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.i(TAG, "onCreate."); if (super._onCreate(savedInstanceState)){ goTop(); // skip the header // Mark all as read. // getDb().markAllMentionsRead(); markAllRead(); boolean shouldRetrieve = false; //FIXME: 该子类页面全部使用了这个统一的计时器,导致进入Mention等分页面后经常不会自动刷新 long lastRefreshTime = mPreferences.getLong( Preferences.LAST_TWEET_REFRESH_KEY, 0); long nowTime = Utils.getNowTime(); long diff = nowTime - lastRefreshTime; Log.i(TAG, "Last refresh was " + diff + " ms ago."); if (diff > REFRESH_THRESHOLD) { shouldRetrieve = true; } else if (Utils.isTrue(savedInstanceState, SIS_RUNNING_KEY)) { // Check to see if it was running a send or retrieve task. // It makes no sense to resend the send request (don't want dupes) // so we instead retrieve (refresh) to see if the message has // posted. Log.i(TAG, "Was last running a retrieve or send task. Let's refresh."); shouldRetrieve = true; } if (shouldRetrieve) { doRetrieve(); } long lastFollowersRefreshTime = mPreferences.getLong( Preferences.LAST_FOLLOWERS_REFRESH_KEY, 0); diff = nowTime - lastFollowersRefreshTime; Log.i(TAG, "Last followers refresh was " + diff + " ms ago."); // Should Refresh Followers if (diff > FOLLOWERS_REFRESH_THRESHOLD && (mRetrieveTask == null || mRetrieveTask.getStatus() != GenericTask.Status.RUNNING)) { Log.i(TAG, "Refresh followers."); doRetrieveFollowers(); } return true; }else{ return false; } } @Override protected void onResume() { Log.i(TAG, "onResume."); if (lastPosition != 0) { mTweetList.setSelection(lastPosition); } super.onResume(); checkIsLogedIn(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } @Override protected void onRestoreInstanceState(Bundle bundle) { super.onRestoreInstanceState(bundle); // mTweetEdit.updateCharsRemain(); } @Override protected void onDestroy() { Log.i(TAG, "onDestroy."); super.onDestroy(); taskManager.cancelAll(); } @Override protected void onPause() { Log.i(TAG, "onPause."); super.onPause(); lastPosition = mTweetList.getFirstVisiblePosition(); } @Override protected void onRestart() { Log.i(TAG, "onRestart."); super.onRestart(); } @Override protected void onStart() { Log.i(TAG, "onStart."); super.onStart(); } @Override protected void onStop() { Log.i(TAG, "onStop."); super.onStop(); } // UI helpers. @Override protected String getActivityTitle() { // TODO Auto-generated method stub return null; } @Override protected void adapterRefresh() { mTweetAdapter.notifyDataSetChanged(); mTweetAdapter.refresh(); } // Retrieve interface public void updateProgress(String progress) { mProgressText.setText(progress); } public void draw() { mTweetAdapter.refresh(); } public void goTop() { Log.i(TAG, "goTop."); mTweetList.setSelection(1); } private void doRetrieveFollowers() { Log.i(TAG, "Attempting followers retrieve."); if (mFollowersRetrieveTask != null && mFollowersRetrieveTask.getStatus() == GenericTask.Status.RUNNING){ return; }else{ mFollowersRetrieveTask = new FollowersRetrieveTask(); mFollowersRetrieveTask.setListener(mFollowerRetrieveTaskListener); mFollowersRetrieveTask.execute(); taskManager.addTask(mFollowersRetrieveTask); // Don't need to cancel FollowersTask (assuming it ends properly). mFollowersRetrieveTask.setCancelable(false); } } public void onRetrieveBegin() { mRetrieveCount = 0; updateProgress(getString(R.string.page_status_refreshing)); } public void doRetrieve() { Log.i(TAG, "Attempting retrieve."); // 旋转刷新按钮 animRotate(refreshButton); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING){ return; }else{ mRetrieveTask = new RetrieveTask(); mRetrieveTask.setListener(mRetrieveTaskListener); mRetrieveTask.execute(); // Add Task to manager taskManager.addTask(mRetrieveTask); } } // for Retrievable interface public ImageButton getRefreshButton() { return refreshButton; } private class RetrieveTask extends GenericTask{ @Override protected TaskResult _doInBackground(TaskParams... params) { List<com.ch_linghu.fanfoudroid.weibo.Status> statusList; String maxId = fetchMaxId(); // getDb().fetchMaxMentionId(); try { statusList = getMessageSinceId(maxId); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } ArrayList<Tweet> tweets = new ArrayList<Tweet>(); HashSet<String> imageUrls = new HashSet<String>(); for (com.ch_linghu.fanfoudroid.weibo.Status status : statusList) { if (isCancelled()) { return TaskResult.CANCELLED; } tweets.add(Tweet.create(status)); if (isCancelled()) { return TaskResult.CANCELLED; } } mRetrieveCount = addMessages(tweets, false); // getDb().addMentions(tweets, false); return TaskResult.OK; } } private class FollowersRetrieveTask extends GenericTask{ @Override protected TaskResult _doInBackground(TaskParams... params) { try { // TODO: 目前仅做新API兼容性改动,待完善Follower处理 IDs followers = getApi().getFollowersIDs(); List<String> followerIds = Arrays.asList(followers.getIDs()); getDb().syncFollowers(followerIds); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } return TaskResult.OK; } } // GET MORE TASK private class GetMoreTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { List<com.ch_linghu.fanfoudroid.weibo.Status> statusList; String minId = fetchMinId(); // getDb().fetchMaxMentionId(); if(minId == null){ return TaskResult.FAILED; } try { statusList = getMoreMessageFromId(minId); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } if(statusList == null){ return TaskResult.FAILED; } ArrayList<Tweet> tweets = new ArrayList<Tweet>(); HashSet<String> imageUrls = new HashSet<String>(); for (com.ch_linghu.fanfoudroid.weibo.Status status : statusList) { if (isCancelled()) { return TaskResult.CANCELLED; } tweets.add(Tweet.create(status)); if (isCancelled()) { return TaskResult.CANCELLED; } } addMessages(tweets, false); // getDb().addMentions(tweets, false); return TaskResult.OK; } } private TaskListener getMoreListener = new TaskAdapter() { @Override public String getName() { return "getMore"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { super.onPostExecute(task, result); draw(); getRefreshButton().clearAnimation(); loadMoreGIF.setVisibility(View.GONE); } }; public void doGetMore() { Log.i(TAG, "Attempting getMore."); // 旋转刷新按钮 animRotate(refreshButton); if (mGetMoreTask != null && mGetMoreTask.getStatus() == GenericTask.Status.RUNNING){ return; }else{ mGetMoreTask = new GetMoreTask(); mGetMoreTask.setListener(getMoreListener); mGetMoreTask.execute(); // Add Task to manager taskManager.addTask(mGetMoreTask); } } }
Java
/** * */ package com.ch_linghu.fanfoudroid.ui.module; import java.text.ParseException; import java.util.Date; import java.util.List; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.preference.PreferenceManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.data.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.data.db.UserInfoTable; import com.ch_linghu.fanfoudroid.helper.Preferences; import com.ch_linghu.fanfoudroid.helper.ProfileImageCacheCallback; import com.ch_linghu.fanfoudroid.helper.Utils; public class UserCursorAdapter extends CursorAdapter implements TweetAdapter { private static final String TAG = "TweetCursorAdapter"; private Context mContext; public UserCursorAdapter(Context context, Cursor cursor) { super(context, cursor); mContext = context; if (context != null) { mInflater = LayoutInflater.from(context); } if (cursor != null) { mScreenNametColumn=cursor.getColumnIndexOrThrow(UserInfoTable.FIELD_USER_SCREEN_NAME); mUserIdColumn=cursor.getColumnIndexOrThrow(UserInfoTable._ID); mProfileImageUrlColumn=cursor.getColumnIndexOrThrow(UserInfoTable.FIELD_PROFILE_IMAGE_URL); // mLastStatusColumn=cursor.getColumnIndexOrThrow(UserInfoTable.FIELD_LAST_STATUS); } mMetaBuilder = new StringBuilder(); } private LayoutInflater mInflater; private int mScreenNametColumn; private int mUserIdColumn; private int mProfileImageUrlColumn; //private int mLastStatusColumn; private StringBuilder mMetaBuilder; private ProfileImageCacheCallback callback = new ProfileImageCacheCallback(){ @Override public void refresh(String url, Bitmap bitmap) { UserCursorAdapter.this.refresh(); } }; @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = mInflater.inflate(R.layout.follower_item, parent, false); Log.i(TAG,"load newView"); UserCursorAdapter.ViewHolder holder = new ViewHolder(); holder.screenName=(TextView) view.findViewById(R.id.screen_name); holder.profileImage=(ImageView)view.findViewById(R.id.profile_image); //holder.lastStatus=(TextView) view.findViewById(R.id.last_status); holder.userId=(TextView) view.findViewById(R.id.user_id); view.setTag(holder); return view; } private static class ViewHolder { public TextView screenName; public TextView userId; public TextView lastStatus; public ImageView profileImage; } @Override public void bindView(View view, Context context, Cursor cursor) { UserCursorAdapter.ViewHolder holder = (UserCursorAdapter.ViewHolder) view .getTag(); Log.i(TAG, "cursor count="+cursor.getCount()); Log.i(TAG,"holder is null?"+(holder==null?"yes":"no")); SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext);; boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true); String profileImageUrl = cursor.getString(mProfileImageUrlColumn); if (useProfileImage){ if (!Utils.isEmpty(profileImageUrl)) { holder.profileImage.setImageBitmap(TwitterApplication.mProfileImageCacheManager .get(profileImageUrl, callback)); } }else{ holder.profileImage.setVisibility(View.GONE); } holder.screenName.setText(cursor.getString(mScreenNametColumn)); holder.userId.setText(cursor.getString(mUserIdColumn)); } @Override public void refresh() { getCursor().requery(); } }
Java
package com.ch_linghu.fanfoudroid.ui.module; import com.ch_linghu.fanfoudroid.R; import android.content.Context; import android.content.res.Resources; import android.graphics.Color; import android.text.Layout; import android.text.Spannable; import android.text.SpannableString; import android.text.Spanned; import android.text.style.ForegroundColorSpan; import android.text.style.URLSpan; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.TextView; public class MyTextView extends TextView { public MyTextView(Context context) { super(context); setLinksClickable(false); Resources res = getResources(); int color = res.getColor(R.color.link_color); setLinkTextColor(color); } public MyTextView(Context context, AttributeSet attrs) { super(context, attrs); setLinksClickable(false); Resources res = getResources(); int color = res.getColor(R.color.link_color); setLinkTextColor(color); } private URLSpan mCurrentLink; private ForegroundColorSpan mLinkFocusStyle = new ForegroundColorSpan( Color.RED); @Override public boolean onTouchEvent(MotionEvent event) { CharSequence text = getText(); int action = event.getAction(); if (!(text instanceof Spannable)) { return super.onTouchEvent(event); } Spannable buffer = (Spannable) text; if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_MOVE) { TextView widget = this; int x = (int) event.getX(); int y = (int) event.getY(); x -= widget.getTotalPaddingLeft(); y -= widget.getTotalPaddingTop(); x += widget.getScrollX(); y += widget.getScrollY(); Layout layout = widget.getLayout(); int line = layout.getLineForVertical(y); int off = layout.getOffsetForHorizontal(line, x); URLSpan[] link = buffer.getSpans(off, off, URLSpan.class); if (link.length != 0) { if (action == MotionEvent.ACTION_UP) { if (mCurrentLink == link[0]) { link[0].onClick(widget); } mCurrentLink = null; buffer.removeSpan(mLinkFocusStyle); } else if (action == MotionEvent.ACTION_DOWN) { mCurrentLink = link[0]; buffer.setSpan(mLinkFocusStyle, buffer.getSpanStart(link[0]), buffer .getSpanEnd(link[0]), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } return true; } } mCurrentLink = null; buffer.removeSpan(mLinkFocusStyle); return super.onTouchEvent(event); } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid.ui.module; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.view.Gravity; import android.view.View; import android.view.WindowManager.LayoutParams; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.GridView; import android.widget.SimpleAdapter; import android.widget.Toast; import com.ch_linghu.fanfoudroid.BrowseActivity; import com.ch_linghu.fanfoudroid.DmActivity; import com.ch_linghu.fanfoudroid.FavoritesActivity; import com.ch_linghu.fanfoudroid.FollowersActivity; import com.ch_linghu.fanfoudroid.FollowingActivity; import com.ch_linghu.fanfoudroid.MentionActivity; import com.ch_linghu.fanfoudroid.ProfileActivity; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterActivity; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.UserTimelineActivity; import com.ch_linghu.fanfoudroid.helper.Preferences; /** * 顶部主菜单切换浮动层 * * @author lds * */ public class MenuDialog extends Dialog { private static final int PAGE_MINE = 0; private static final int PAGE_PROFILE = 1; private static final int PAGE_FOLLOWERS = 2; private static final int PAGE_FOLLOWING = 3; private static final int PAGE_HOME = 4; private static final int PAGE_MENTIONS = 5; private static final int PAGE_BROWSE = 6; private static final int PAGE_FAVORITES = 7; private static final int PAGE_MESSAGE = 8; private List<int[]> pages = new ArrayList<int[]>(); { pages.add(new int[] { R.drawable.menu_tweets, R.string.pages_mine }); pages.add(new int[] { R.drawable.menu_profile, R.string.pages_profile }); pages.add(new int[] { R.drawable.menu_followers, R.string.pages_followers }); pages.add(new int[] { R.drawable.menu_following, R.string.pages_following }); pages.add(new int[] { R.drawable.menu_list, R.string.pages_home }); pages.add(new int[] { R.drawable.menu_mentions, R.string.pages_mentions }); pages.add(new int[] { R.drawable.menu_listed, R.string.pages_browse }); pages.add(new int[] { R.drawable.menu_favorites, R.string.pages_search }); pages.add(new int[] { R.drawable.menu_create_list, R.string.pages_message }); }; private GridView gridview; public MenuDialog(Context context, boolean cancelable, OnCancelListener cancelListener) { super(context, cancelable, cancelListener); // TODO Auto-generated constructor stub } public MenuDialog(Context context, int theme) { super(context, theme); // TODO Auto-generated constructor stub } public MenuDialog(Context context) { super(context, R.style.Theme_Transparent); setContentView(R.layout.menu_dialog); // setTitle("Custom Dialog"); setCanceledOnTouchOutside(true); // 设置window属性 LayoutParams a = getWindow().getAttributes(); a.gravity = Gravity.TOP; a.dimAmount = 0; // 去背景遮盖 getWindow().setAttributes(a); initMenu(); } public void setPosition(int x, int y) { LayoutParams a = getWindow().getAttributes(); if (-1 != x) a.x = x; if (-1 != y) a.y = y; getWindow().setAttributes(a); } private void goTo(Class<?> cls) { if (getOwnerActivity().getClass() != cls) { dismiss(); Intent intent = new Intent(); intent.setClass(getContext(), cls); getContext().startActivity(intent); } else { String msg = getContext().getString(R.string.page_status_same_page); Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show(); } } private void initMenu() { // 准备要添加的数据条目 List<Map<String, Object>> items = new ArrayList<Map<String, Object>>(); for (int[] item : pages) { Map<String, Object> map = new HashMap<String, Object>(); map.put("image", item[0]); map.put("title", getContext().getString(item[1]) ); items.add(map); } // 实例化一个适配器 SimpleAdapter adapter = new SimpleAdapter(getContext(), items, // data R.layout.menu_item, // grid item layout new String[] { "title", "image" }, // data's key new int[] { R.id.item_text, R.id.item_image }); // item view id // 获得GridView实例 gridview = (GridView) findViewById(R.id.mygridview); // 将GridView和数据适配器关联 gridview.setAdapter(adapter); } public void bindEvent(Activity activity) { setOwnerActivity(activity); // 绑定监听器 gridview.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { switch (position) { case PAGE_MINE: String user = TwitterApplication.getMyselfId(); //FIXME: 目前没有方便的从ID获得ScreenName的方法, // 等完成UserInfo表操作之后修正此处 String name = "你自己"; Intent intent = UserTimelineActivity.createIntent(user, name); intent.setClass(getContext(), UserTimelineActivity.class); getContext().startActivity(intent); break; case PAGE_PROFILE: goTo(ProfileActivity.class); break; case PAGE_FOLLOWERS: goTo(FollowersActivity.class); break; case PAGE_FOLLOWING: goTo(FollowingActivity.class); break; case PAGE_HOME: goTo(TwitterActivity.class); break; case PAGE_MENTIONS: goTo(MentionActivity.class); break; case PAGE_BROWSE: goTo(BrowseActivity.class); break; case PAGE_FAVORITES: goTo(FavoritesActivity.class); break; case PAGE_MESSAGE: goTo(DmActivity.class); break; } } }); Button close_button = (Button) findViewById(R.id.close_menu); close_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); } }
Java
/** * */ package com.ch_linghu.fanfoudroid.ui.module; import java.text.ParseException; import java.util.Date; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.preference.PreferenceManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.data.db.StatusTable; import com.ch_linghu.fanfoudroid.data.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.helper.Preferences; import com.ch_linghu.fanfoudroid.helper.ProfileImageCacheCallback; import com.ch_linghu.fanfoudroid.helper.Utils; public class TweetCursorAdapter extends CursorAdapter implements TweetAdapter { private static final String TAG = "TweetCursorAdapter"; private Context mContext; public TweetCursorAdapter(Context context, Cursor cursor) { super(context, cursor); mContext = context; if (context != null) { mInflater = LayoutInflater.from(context); } if (cursor != null) { //TODO: 可使用: //Tweet tweet = StatusTable.parseCursor(cursor); mUserTextColumn = cursor .getColumnIndexOrThrow(StatusTable.FIELD_USER_SCREEN_NAME); mTextColumn = cursor .getColumnIndexOrThrow(StatusTable.FIELD_TEXT); mProfileImageUrlColumn = cursor .getColumnIndexOrThrow(StatusTable.FIELD_PROFILE_IMAGE_URL); mCreatedAtColumn = cursor .getColumnIndexOrThrow(StatusTable.FIELD_CREATED_AT); mSourceColumn = cursor .getColumnIndexOrThrow(StatusTable.FIELD_SOURCE); mInReplyToScreenName = cursor .getColumnIndexOrThrow(StatusTable.FIELD_IN_REPLY_TO_SCREEN_NAME); mFavorited = cursor .getColumnIndexOrThrow(StatusTable.FIELD_FAVORITED); mThumbnailPic = cursor .getColumnIndexOrThrow(StatusTable.FIELD_PIC_THUMB); mMiddlePic = cursor .getColumnIndexOrThrow(StatusTable.FIELD_PIC_MID); mOriginalPic = cursor .getColumnIndexOrThrow(StatusTable.FIELD_PIC_ORIG); } mMetaBuilder = new StringBuilder(); } private LayoutInflater mInflater; private int mUserTextColumn; private int mTextColumn; private int mProfileImageUrlColumn; private int mCreatedAtColumn; private int mSourceColumn; private int mInReplyToScreenName; private int mFavorited; private int mThumbnailPic; private int mMiddlePic; private int mOriginalPic; private StringBuilder mMetaBuilder; private ProfileImageCacheCallback callback = new ProfileImageCacheCallback(){ @Override public void refresh(String url, Bitmap bitmap) { TweetCursorAdapter.this.refresh(); } }; @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = mInflater.inflate(R.layout.tweet, parent, false); TweetCursorAdapter.ViewHolder holder = new ViewHolder(); holder.tweetUserText = (TextView) view .findViewById(R.id.tweet_user_text); holder.tweetText = (TextView) view.findViewById(R.id.tweet_text); holder.profileImage = (ImageView) view.findViewById(R.id.profile_image); holder.metaText = (TextView) view.findViewById(R.id.tweet_meta_text); holder.fav = (ImageView) view.findViewById(R.id.tweet_fav); holder.has_image = (ImageView) view.findViewById(R.id.tweet_has_image); view.setTag(holder); return view; } private static class ViewHolder { public TextView tweetUserText; public TextView tweetText; public ImageView profileImage; public TextView metaText; public ImageView fav; public ImageView has_image; } @Override public void bindView(View view, Context context, Cursor cursor) { TweetCursorAdapter.ViewHolder holder = (TweetCursorAdapter.ViewHolder) view .getTag(); SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext);; boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true); holder.tweetUserText.setText(cursor.getString(mUserTextColumn)); Utils.setSimpleTweetText(holder.tweetText, cursor.getString(mTextColumn)); String profileImageUrl = cursor.getString(mProfileImageUrlColumn); if (useProfileImage){ if (!Utils.isEmpty(profileImageUrl)) { holder.profileImage.setImageBitmap(TwitterApplication.mProfileImageCacheManager .get(profileImageUrl, callback)); } }else{ holder.profileImage.setVisibility(View.GONE); } if (cursor.getString(mFavorited).equals("true")) { holder.fav.setVisibility(View.VISIBLE); } else { holder.fav.setVisibility(View.GONE); } if (!Utils.isEmpty(cursor.getString(mThumbnailPic))) { holder.has_image.setVisibility(View.VISIBLE); } else { holder.has_image.setVisibility(View.GONE); } try { Date createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(cursor .getString(mCreatedAtColumn)); holder.metaText.setText(Tweet.buildMetaText(mMetaBuilder, createdAt, cursor.getString(mSourceColumn), cursor .getString(mInReplyToScreenName))); } catch (ParseException e) { Log.w(TAG, "Invalid created at data."); } } @Override public void refresh() { getCursor().requery(); } }
Java
package com.ch_linghu.fanfoudroid.ui.module; import java.util.ArrayList; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.data.User; import com.ch_linghu.fanfoudroid.helper.Preferences; import com.ch_linghu.fanfoudroid.helper.ProfileImageCacheCallback; import com.ch_linghu.fanfoudroid.helper.Utils; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.weibo.Weibo; //TODO: /* * 用于用户的Adapter */ public class UserArrayAdapter extends BaseAdapter implements TweetAdapter{ private static final String TAG = "UserArrayAdapter"; private static final String USER_ID="userId"; protected ArrayList<User> mUsers; private Context mContext; protected LayoutInflater mInflater; public UserArrayAdapter(Context context) { mUsers = new ArrayList<User>(); mContext = context; mInflater = LayoutInflater.from(mContext); } @Override public int getCount() { return mUsers.size(); } @Override public Object getItem(int position) { return mUsers.get(position); } @Override public long getItemId(int position) { return position; } private static class ViewHolder { public ImageView profileImage; public TextView screenName; public TextView userId; public TextView lastStatus; public TextView testBtn; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view; SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext); boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true); if (convertView == null) { view = mInflater.inflate(R.layout.follower_item, parent, false); ViewHolder holder = new ViewHolder(); holder.profileImage = (ImageView) view.findViewById(R.id.profile_image); holder.screenName = (TextView) view.findViewById(R.id.screen_name); holder.userId = (TextView) view.findViewById(R.id.user_id); //holder.lastStatus = (TextView) view.findViewById(R.id.last_status); holder.testBtn=(TextView)view.findViewById(R.id.test_btn); view.setTag(holder); } else { view = convertView; } ViewHolder holder = (ViewHolder) view.getTag(); final User user = mUsers.get(position); String profileImageUrl = user.profileImageUrl; if (useProfileImage){ if (!Utils.isEmpty(profileImageUrl)) { holder.profileImage.setImageBitmap(TwitterApplication.mProfileImageCacheManager .get(profileImageUrl, callback)); } }else{ holder.profileImage.setVisibility(View.GONE); } //holder.profileImage.setImageBitmap(ImageManager.mDefaultBitmap); holder.screenName.setText(user.screenName); holder.userId.setText(user.id); //holder.lastStatus.setText(user.lastStatus); holder.testBtn.setText(user.isFollowing?mContext.getString(R.string.general_del_friend):mContext.getString(R.string.general_add_friend)); holder.testBtn.setOnClickListener(user.isFollowing?new OnClickListener(){ @Override public void onClick(View v) { //Toast.makeText(mContext, user.name+"following", Toast.LENGTH_SHORT).show(); delFriend(user.id); }}:new OnClickListener(){ @Override public void onClick(View v) { //Toast.makeText(mContext, user.name+"not following", Toast.LENGTH_SHORT).show(); addFriend(user.id); }}); return view; } public void refresh(ArrayList<User> users) { mUsers = users; notifyDataSetChanged(); } @Override public void refresh() { } private ProfileImageCacheCallback callback = new ProfileImageCacheCallback(){ @Override public void refresh(String url, Bitmap bitmap) { UserArrayAdapter.this.refresh(); } }; /** * 取消关注 * @param id */ private void delFriend(final String id) { Builder diaBuilder = new AlertDialog.Builder(mContext) .setTitle("关注提示").setMessage("确实要取消关注吗?"); diaBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (cancelFollowingTask != null && cancelFollowingTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { cancelFollowingTask = new CancelFollowingTask(); cancelFollowingTask .setListener(cancelFollowingTaskLinstener); TaskParams params = new TaskParams(); params.put(USER_ID, id); cancelFollowingTask.execute(params); } } }); diaBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); Dialog dialog = diaBuilder.create(); dialog.show(); } private GenericTask cancelFollowingTask; /** * 取消关注 * * @author Dino * */ private class CancelFollowingTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { //TODO:userid String userId=params[0].getString(USER_ID); getApi().destroyFriendship(userId); } catch (HttpException e) { Log.w(TAG, "create friend ship error"); return TaskResult.FAILED; } return TaskResult.OK; } } private TaskListener cancelFollowingTaskLinstener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { // followingBtn.setText("添加关注"); // isFollowingText.setText(getResources().getString( // R.string.profile_notfollowing)); // followingBtn.setOnClickListener(setfollowingListener); Toast.makeText(mContext, "取消关注成功", Toast.LENGTH_SHORT).show(); } else if (result == TaskResult.FAILED) { Toast.makeText(mContext, "取消关注失败", Toast.LENGTH_SHORT).show(); } } @Override public String getName() { // TODO Auto-generated method stub return null; } }; private GenericTask setFollowingTask; /** * 设置关注 * @param id */ private void addFriend(String id){ Builder diaBuilder = new AlertDialog.Builder(mContext) .setTitle("关注提示").setMessage("确实要添加关注吗?"); diaBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (setFollowingTask != null && setFollowingTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { setFollowingTask = new SetFollowingTask(); setFollowingTask .setListener(setFollowingTaskLinstener); TaskParams params = new TaskParams(); setFollowingTask.execute(params); } } }); diaBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); Dialog dialog = diaBuilder.create(); dialog.show(); } /** * 设置关注 * * @author Dino * */ private class SetFollowingTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { String userId=params[0].getString(USER_ID); getApi().createFriendship(userId); } catch (HttpException e) { Log.w(TAG, "create friend ship error"); return TaskResult.FAILED; } return TaskResult.OK; } } private TaskListener setFollowingTaskLinstener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { // followingBtn.setText("取消关注"); // isFollowingText.setText(getResources().getString( // R.string.profile_isfollowing)); // followingBtn.setOnClickListener(cancelFollowingListener); Toast.makeText(mContext, "关注成功", Toast.LENGTH_SHORT).show(); } else if (result == TaskResult.FAILED) { Toast.makeText(mContext, "关注失败", Toast.LENGTH_SHORT).show(); } } @Override public String getName() { // TODO Auto-generated method stub return null; } }; public Weibo getApi() { return TwitterApplication.mApi; } }
Java
package com.ch_linghu.fanfoudroid.ui.module; import android.graphics.Color; import android.text.Editable; import android.text.InputFilter; import android.text.Selection; import android.text.TextWatcher; import android.view.View.OnKeyListener; import android.widget.EditText; import android.widget.TextView; public class TweetEdit { private EditText mEditText; private TextView mCharsRemainText; private int originTextColor; public TweetEdit(EditText editText, TextView charsRemainText) { mEditText = editText; mCharsRemainText = charsRemainText; originTextColor = mCharsRemainText.getTextColors().getDefaultColor(); mEditText.addTextChangedListener(mTextWatcher); mEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter( MAX_TWEET_INPUT_LENGTH) }); } private static final int MAX_TWEET_LENGTH = 140; private static final int MAX_TWEET_INPUT_LENGTH = 400; public void setTextAndFocus(String text, boolean start) { setText(text); Editable editable = mEditText.getText(); if (!start){ Selection.setSelection(editable, editable.length()); }else{ Selection.setSelection(editable, 0); } mEditText.requestFocus(); } public void setText(String text) { mEditText.setText(text); updateCharsRemain(); } private TextWatcher mTextWatcher = new TextWatcher() { @Override public void afterTextChanged(Editable e) { updateCharsRemain(); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } }; public void updateCharsRemain() { int remaining = MAX_TWEET_LENGTH - mEditText.length(); if (remaining < 0 ) { mCharsRemainText.setTextColor(Color.RED); } else { mCharsRemainText.setTextColor(originTextColor); } mCharsRemainText.setText(remaining + ""); } public String getText() { return mEditText.getText().toString(); } public void setEnabled(boolean b) { mEditText.setEnabled(b); } public void setOnKeyListener(OnKeyListener listener) { mEditText.setOnKeyListener(listener); } public void addTextChangedListener(TextWatcher watcher){ mEditText.addTextChangedListener(watcher); } public void requestFocus() { mEditText.requestFocus(); } public EditText getEditText() { return mEditText; } }
Java
package com.ch_linghu.fanfoudroid.ui.module; import java.util.ArrayList; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.helper.ImageCache; import com.ch_linghu.fanfoudroid.helper.Preferences; import com.ch_linghu.fanfoudroid.helper.ProfileImageCacheCallback; import com.ch_linghu.fanfoudroid.helper.ProfileImageCacheManager; import com.ch_linghu.fanfoudroid.helper.Utils; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.preference.PreferenceManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class TweetArrayAdapter extends BaseAdapter implements TweetAdapter { private static final String TAG = "TweetArrayAdapter"; protected ArrayList<Tweet> mTweets; private Context mContext; protected LayoutInflater mInflater; protected StringBuilder mMetaBuilder; private ProfileImageCacheCallback callback = new ProfileImageCacheCallback(){ @Override public void refresh(String url, Bitmap bitmap) { TweetArrayAdapter.this.refresh(); } }; public TweetArrayAdapter(Context context) { mTweets = new ArrayList<Tweet>(); mContext = context; mInflater = LayoutInflater.from(mContext); mMetaBuilder = new StringBuilder(); } @Override public int getCount() { return mTweets.size(); } @Override public Object getItem(int position) { return mTweets.get(position); } @Override public long getItemId(int position) { return position; } private static class ViewHolder { public TextView tweetUserText; public TextView tweetText; public ImageView profileImage; public TextView metaText; public ImageView fav; public ImageView has_image; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view; SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext); boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true); if (convertView == null) { view = mInflater.inflate(R.layout.tweet, parent, false); ViewHolder holder = new ViewHolder(); holder.tweetUserText = (TextView) view .findViewById(R.id.tweet_user_text); holder.tweetText = (TextView) view.findViewById(R.id.tweet_text); holder.profileImage = (ImageView) view .findViewById(R.id.profile_image); holder.metaText = (TextView) view .findViewById(R.id.tweet_meta_text); holder.fav = (ImageView) view.findViewById(R.id.tweet_fav); holder.has_image = (ImageView) view.findViewById(R.id.tweet_has_image); view.setTag(holder); } else { view = convertView; } ViewHolder holder = (ViewHolder) view.getTag(); Tweet tweet = mTweets.get(position); holder.tweetUserText.setText(tweet.screenName); Utils.setSimpleTweetText(holder.tweetText, tweet.text); // holder.tweetText.setText(tweet.text, BufferType.SPANNABLE); String profileImageUrl = tweet.profileImageUrl; if (useProfileImage){ if (!Utils.isEmpty(profileImageUrl)) { holder.profileImage.setImageBitmap(TwitterApplication.mProfileImageCacheManager .get(profileImageUrl, callback)); } }else{ holder.profileImage.setVisibility(View.GONE); } holder.metaText.setText(Tweet.buildMetaText(mMetaBuilder, tweet.createdAt, tweet.source, tweet.inReplyToScreenName)); if (tweet.favorited.equals("true")) { holder.fav.setVisibility(View.VISIBLE); } else { holder.fav.setVisibility(View.GONE); } if (!Utils.isEmpty(tweet.thumbnail_pic)) { holder.has_image.setVisibility(View.VISIBLE); } else { holder.has_image.setVisibility(View.GONE); } return view; } public void refresh(ArrayList<Tweet> tweets) { mTweets = tweets; notifyDataSetChanged(); } @Override public void refresh() { notifyDataSetChanged(); } }
Java
package com.ch_linghu.fanfoudroid.ui.module; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.AbsListView; import android.widget.ListView; public class MyListView extends ListView implements ListView.OnScrollListener { private int mScrollState = OnScrollListener.SCROLL_STATE_IDLE; public MyListView(Context context, AttributeSet attrs) { super(context, attrs); setOnScrollListener(this); } @Override public boolean onInterceptTouchEvent(MotionEvent event) { boolean result = super.onInterceptTouchEvent(event); if (mScrollState == OnScrollListener.SCROLL_STATE_FLING) { return true; } return result; } private OnNeedMoreListener mOnNeedMoreListener; public static interface OnNeedMoreListener { public void needMore(); } public void setOnNeedMoreListener(OnNeedMoreListener onNeedMoreListener) { mOnNeedMoreListener = onNeedMoreListener; } private int mFirstVisibleItem; @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (mOnNeedMoreListener == null) { return; } if (firstVisibleItem != mFirstVisibleItem) { if (firstVisibleItem + visibleItemCount >= totalItemCount) { mOnNeedMoreListener.needMore(); } } else { mFirstVisibleItem = firstVisibleItem; } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { mScrollState = scrollState; } }
Java
package com.ch_linghu.fanfoudroid.ui.module; import android.widget.ListAdapter; public interface TweetAdapter extends ListAdapter{ void refresh(); }
Java
package com.ch_linghu.fanfoudroid; import java.util.List; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.widget.ListView; import android.widget.Toast; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.ui.base.UserArrayBaseActivity; import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter; import com.ch_linghu.fanfoudroid.weibo.Paging; public class FollowersActivity extends UserArrayBaseActivity { private ListView mUserList; private UserArrayAdapter mAdapter; private static final String TAG = "FollowersActivity"; private String userId; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FOLLOWERS"; private static final String USER_ID = "userId"; private int currentPage=1; private int followersCount=0; private static final double PRE_PAGE_COUNT=100.0;//官方分页为每页100 private int pageCount=0; private String[] ids; @Override protected boolean _onCreate(Bundle savedInstanceState) { Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null) { this.userId = extras.getString(USER_ID); } else { // 获取登录用户id // SharedPreferences preferences = PreferenceManager // .getDefaultSharedPreferences(this); // userId = preferences.getString(Preferences.CURRENT_USER_ID, // TwitterApplication.mApi.getUserId()); userId=TwitterApplication.getMyselfId(); } Uri data = intent.getData(); if (data != null) { userId = data.getLastPathSegment(); } if (super._onCreate(savedInstanceState)) { String myself = TwitterApplication.getMyselfId(); Toast.makeText(getBaseContext(), myself+"@"+getUserId(), Toast.LENGTH_SHORT); if(getUserId()==myself){ setHeaderTitle("关注我的人"); } return true; }else{ return false; } } public static Intent createIntent(String userId) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra(USER_ID, userId); return intent; } @Override public Paging getNextPage() { currentPage+=1; return new Paging(currentPage); } @Override protected String getUserId() { return this.userId; } @Override public Paging getCurrentPage() { return new Paging(this.currentPage); } @Override protected List<com.ch_linghu.fanfoudroid.weibo.User> getUsers( String userId, Paging page) throws HttpException { return getApi().getFollowersList(userId, page); } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.Menu; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.data.db.StatusTable; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity; import com.ch_linghu.fanfoudroid.weibo.Paging; import com.ch_linghu.fanfoudroid.weibo.Status; public class MentionActivity extends TwitterCursorBaseActivity { private static final String TAG = "MentionActivity"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.REPLIES"; static final int DIALOG_WRITE_ID = 0; public static Intent createIntent(Context context) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); return intent; } public static Intent createNewTaskIntent(Context context) { Intent intent = createIntent(context); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); return intent; } @Override protected boolean _onCreate(Bundle savedInstanceState) { if (super._onCreate(savedInstanceState)){ setHeaderTitle("@提到我的"); return true; }else{ return false; } } @Override public boolean onCreateOptionsMenu(Menu menu) { return super.onCreateOptionsMenu(menu); } @Override protected Cursor fetchMessages() { return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_MENTION); } @Override protected void markAllRead() { getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_MENTION); } @Override protected String getActivityTitle() { return getResources().getString(R.string.page_title_mentions); } // for Retrievable interface @Override public String fetchMaxId() { return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_MENTION); } @Override public List<Status> getMessageSinceId(String maxId) throws HttpException { if (maxId != null){ return getApi().getMentions(new Paging(maxId)); }else{ return getApi().getMentions(); } } @Override public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) { return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_MENTION, isUnread); } @Override public String fetchMinId() { return getDb().fetchMinTweetId(getUserId(), StatusTable.TYPE_MENTION); } @Override public List<Status> getMoreMessageFromId(String minId) throws HttpException { Paging paging = new Paging(1, 20); paging.setMaxId(minId); return getApi().getMentions(paging); } @Override public int getDatabaseType() { return StatusTable.TYPE_MENTION; } @Override public String getUserId() { return TwitterApplication.getMyselfId(); } }
Java
package com.ch_linghu.fanfoudroid.http; /** * HTTP StatusCode is not 200 */ public class HttpException extends Exception { private int statusCode = -1; public HttpException(String msg) { super(msg); } public HttpException(Exception cause) { super(cause); } public HttpException(String msg, int statusCode) { super(msg); this.statusCode = statusCode; } public HttpException(String msg, Exception cause) { super(msg, cause); } public HttpException(String msg, Exception cause, int statusCode) { super(msg, cause); this.statusCode = statusCode; } public int getStatusCode() { return this.statusCode; } }
Java
package com.ch_linghu.fanfoudroid.http; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.util.ArrayList; import javax.net.ssl.SSLHandshakeException; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.NoHttpResponseException; import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthState; import org.apache.http.auth.Credentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.protocol.ClientContext; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.params.ConnManagerParams; import org.apache.http.conn.params.ConnRoutePNames; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HttpContext; import android.util.Log; import com.ch_linghu.fanfoudroid.weibo.Configuration; import com.ch_linghu.fanfoudroid.weibo.RefuseError; /** * Wrap of org.apache.http.impl.client.DefaultHttpClient * * @author lds * */ public class HttpClient { private static final String TAG = "HttpClient"; private final static boolean DEBUG = Configuration.getDebug(); /** OK: Success! */ public static final int OK = 200; /** Not Modified: There was no new data to return. */ public static final int NOT_MODIFIED = 304; /** Bad Request: The request was invalid. An accompanying error message will explain why. This is the status code will be returned during rate limiting. */ public static final int BAD_REQUEST = 400; /** Not Authorized: Authentication credentials were missing or incorrect. */ public static final int NOT_AUTHORIZED = 401; /** Forbidden: The request is understood, but it has been refused. An accompanying error message will explain why. */ public static final int FORBIDDEN = 403; /** Not Found: The URI requested is invalid or the resource requested, such as a user, does not exists. */ public static final int NOT_FOUND = 404; /** Not Acceptable: Returned by the Search API when an invalid format is specified in the request. */ public static final int NOT_ACCEPTABLE = 406; /** Internal Server Error: Something is broken. Please post to the group so the Weibo team can investigate. */ public static final int INTERNAL_SERVER_ERROR = 500; /** Bad Gateway: Weibo is down or being upgraded. */ public static final int BAD_GATEWAY = 502; /** Service Unavailable: The Weibo servers are up, but overloaded with requests. Try again later. The search and trend methods use this to indicate when you are being rate limited. */ public static final int SERVICE_UNAVAILABLE = 503; private static final int CONNECTION_TIMEOUT_MS = 30 * 1000; private static final int SOCKET_TIMEOUT_MS = 30 * 1000; public static final int RETRIEVE_LIMIT = 20; public static final int RETRIED_TIME = 3; private static final String SERVER_HOST = "api.fanfou.com"; private DefaultHttpClient mClient; private AuthScope mAuthScope; private BasicHttpContext localcontext; private String mUserId; private String mPassword; private static boolean isAuthenticationEnabled = false; public HttpClient() { prepareHttpClient(); } /** * @param user_id auth user * @param password auth password */ public HttpClient(String user_id, String password) { prepareHttpClient(); setCredentials(user_id, password); } /** * Empty the credentials */ public void reset() { setCredentials("", ""); } /** * @return authed user id */ public String getUserId() { return mUserId; } /** * @return authed user password */ public String getPassword() { return mPassword; } /** * @param hostname the hostname (IP or DNS name) * @param port the port number. -1 indicates the scheme default port. * @param scheme the name of the scheme. null indicates the default scheme */ public void setProxy(String host, int port, String scheme) { HttpHost proxy = new HttpHost(host, port, scheme); mClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } public void removeProxy() { mClient.getParams().removeParameter(ConnRoutePNames.DEFAULT_PROXY); } private void enableDebug() { Log.i(TAG, "enable apache.http debug"); java.util.logging.Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.FINEST); java.util.logging.Logger.getLogger("org.apache.http.wire").setLevel(java.util.logging.Level.FINER); java.util.logging.Logger.getLogger("org.apache.http.headers").setLevel(java.util.logging.Level.OFF); /* System.setProperty("log.tag.org.apache.http", "VERBOSE"); System.setProperty("log.tag.org.apache.http.wire", "VERBOSE"); System.setProperty("log.tag.org.apache.http.headers", "VERBOSE"); 在这里使用System.setProperty设置不会生效, 原因不明, 必须在终端上输入以下命令方能开启http调试信息: > adb shell setprop log.tag.org.apache.http VERBOSE > adb shell setprop log.tag.org.apache.http.wire VERBOSE > adb shell setprop log.tag.org.apache.http.headers VERBOSE */ } /** * Setup DefaultHttpClient * * Use ThreadSafeClientConnManager. * */ private void prepareHttpClient() { if (DEBUG) { enableDebug(); } // Create and initialize HTTP parameters HttpParams params = new BasicHttpParams(); ConnManagerParams.setMaxTotalConnections(params, 10); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // Create and initialize scheme registry SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory .getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory .getSocketFactory(), 443)); // Create an HttpClient with the ThreadSafeClientConnManager. ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); mClient = new DefaultHttpClient(cm, params); // TODO: need to release this connection in httpRequest() // cm.releaseConnection(conn, validDuration, timeUnit); // Setup BasicAuth BasicScheme basicScheme = new BasicScheme(); mAuthScope = new AuthScope(SERVER_HOST, AuthScope.ANY_PORT); // mClient.setAuthSchemes(authRegistry); mClient.setCredentialsProvider(new BasicCredentialsProvider()); // Generate BASIC scheme object and stick it to the local // execution context localcontext = new BasicHttpContext(); localcontext.setAttribute("preemptive-auth", basicScheme); // first request interceptor mClient.addRequestInterceptor(preemptiveAuth, 0); } /** * HttpRequestInterceptor for DefaultHttpClient */ private HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() { @Override public void process(final HttpRequest request, final HttpContext context) { AuthState authState = (AuthState) context .getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context .getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } } }; /** * Setup Credentials for HTTP Basic Auth * * @param username * @param password */ public void setCredentials(String username, String password) { mUserId = username; mPassword = password; mClient.getCredentialsProvider().setCredentials(mAuthScope, new UsernamePasswordCredentials(username, password)); isAuthenticationEnabled = true; } public Response post(String url, ArrayList<BasicNameValuePair> postParams, boolean authenticated) throws HttpException { if (null == postParams) { postParams = new ArrayList<BasicNameValuePair>(); } return httpRequest(url, postParams, authenticated, HttpPost.METHOD_NAME); } public Response post(String url, ArrayList<BasicNameValuePair> params) throws HttpException { return httpRequest(url, params, false, HttpPost.METHOD_NAME); } public Response post(String url, boolean authenticated) throws HttpException { return httpRequest(url, null, authenticated, HttpPost.METHOD_NAME); } public Response post(String url) throws HttpException { return httpRequest(url, null, false, HttpPost.METHOD_NAME); } public Response post(String url, File file) throws HttpException { return httpRequest(url, null, file, false, HttpPost.METHOD_NAME); } /** * POST一个文件 * * @param url * @param file * @param authenticate * @return * @throws HttpException */ public Response post(String url, File file, boolean authenticate) throws HttpException { return httpRequest(url, null, file, authenticate, HttpPost.METHOD_NAME); } public Response get(String url, ArrayList<BasicNameValuePair> params, boolean authenticated) throws HttpException { return httpRequest(url, params, authenticated, HttpGet.METHOD_NAME); } public Response get(String url, ArrayList<BasicNameValuePair> params) throws HttpException { return httpRequest(url, params, false, HttpGet.METHOD_NAME); } public Response get(String url) throws HttpException { return httpRequest(url, null, false, HttpGet.METHOD_NAME); } public Response get(String url, boolean authenticated) throws HttpException { return httpRequest(url, null, authenticated, HttpGet.METHOD_NAME); } public Response httpRequest(String url, ArrayList<BasicNameValuePair> postParams, boolean authenticated, String httpMethod) throws HttpException { return httpRequest(url, postParams, null, authenticated, httpMethod); } /** * Execute the DefaultHttpClient * * @param url * target * @param postParams * @param file * can be NULL * @param authenticated * need or not * @param httpMethod * HttpPost.METHOD_NAME * HttpGet.METHOD_NAME * HttpDelete.METHOD_NAME * @return Response from server * @throws HttpException 此异常包装了一系列底层异常 <br /><br /> * 1. 底层异常, 可使用getCause()查看: <br /> * <li>URISyntaxException, 由`new URI` 引发的.</li> * <li>IOException, 由`createMultipartEntity` 或 `UrlEncodedFormEntity` 引发的.</li> * <li>IOException和ClientProtocolException, 由`HttpClient.execute` 引发的.</li><br /> * * 2. 当响应码不为200时报出的各种子类异常: * <li>HttpRequestException, 通常发生在请求的错误,如请求错误了 网址导致404等, 抛出此异常, * 首先检查request log, 确认不是人为错误导致请求失败</li> * <li>HttpAuthException, 通常发生在Auth失败, 检查用于验证登录的用户名/密码/KEY等</li> * <li>HttpRefusedException, 通常发生在服务器接受到请求, 但拒绝请求, 可是多种原因, 具体原因 * 服务器会返回拒绝理由, 调用HttpRefusedException#getError#getMessage查看</li> * <li>HttpServerException, 通常发生在服务器发生错误时, 检查服务器端是否在正常提供服务</li> * <li>HttpException, 其他未知错误.</li> */ public Response httpRequest(String url, ArrayList<BasicNameValuePair> postParams, File file, boolean authenticated, String httpMethod) throws HttpException { Log.i(TAG, "Sending " + httpMethod + " request to " + url); long startTime = System.currentTimeMillis(); URI uri = createURI(url); HttpResponse response = null; Response res = null; HttpUriRequest method = null; // Create POST, GET or DELETE METHOD method = createMethod(httpMethod, uri, file, postParams); // Setup ConnectionParams SetupHTTPConnectionParams(method); // Execute Request try { response = mClient.execute(method,localcontext); res = new Response(response); } catch (ClientProtocolException e) { Log.e(TAG, e.getMessage(), e); throw new HttpException(e.getMessage(), e); } catch (IOException ioe) { throw new HttpException(ioe.getMessage(), ioe); } if (response != null) { int statusCode = response.getStatusLine().getStatusCode(); // It will throw a weiboException while status code is not 200 HandleResponseStatusCode(statusCode, res); } else { Log.e(TAG, "response is null"); } long endTime = System.currentTimeMillis(); Log.d(TAG, "Http request in " + (endTime - startTime)); //TODO: response内容DEBUG输出 return res; } /** * CreateURI from URL string * * @param url * @return request URI * @throws HttpException * Cause by URISyntaxException */ private URI createURI(String url) throws HttpException { URI uri; try { uri = new URI(url); } catch (URISyntaxException e) { Log.e(TAG, e.getMessage(), e); throw new HttpException("Invalid URL."); } return uri; } /** * 创建可带一个File的MultipartEntity * * @param filename * 文件名 * @param file * 文件 * @param postParams * 其他POST参数 * @return 带文件和其他参数的Entity * @throws UnsupportedEncodingException */ private MultipartEntity createMultipartEntity(String filename, File file, ArrayList<BasicNameValuePair> postParams) throws UnsupportedEncodingException { MultipartEntity entity = new MultipartEntity(); // Don't try this. Server does not appear to support chunking. // entity.addPart("media", new InputStreamBody(imageStream, "media")); entity.addPart(filename, new FileBody(file)); for (BasicNameValuePair param : postParams) { entity.addPart(param.getName(), new StringBody(param.getValue())); } return entity; } /** * Setup HTTPConncetionParams * * @param method */ private void SetupHTTPConnectionParams(HttpUriRequest method) { HttpConnectionParams.setConnectionTimeout(method.getParams(), CONNECTION_TIMEOUT_MS); HttpConnectionParams .setSoTimeout(method.getParams(), SOCKET_TIMEOUT_MS); mClient.setHttpRequestRetryHandler(requestRetryHandler); method.addHeader("Accept-Encoding", "gzip, deflate"); } /** * Create request method, such as POST, GET, DELETE * * @param httpMethod * "GET","POST","DELETE" * @param uri * 请求的URI * @param file * 可为null * @param postParams * POST参数 * @return httpMethod Request implementations for the various HTTP methods * like GET and POST. * @throws HttpException * createMultipartEntity 或 UrlEncodedFormEntity引发的IOException */ private HttpUriRequest createMethod(String httpMethod, URI uri, File file, ArrayList<BasicNameValuePair> postParams) throws HttpException { HttpUriRequest method; if (httpMethod.equalsIgnoreCase(HttpPost.METHOD_NAME)) { // POST METHOD HttpPost post = new HttpPost(uri); // See this: http://groups.google.com/group/twitter-development-talk/browse_thread/thread/e178b1d3d63d8e3b post.getParams().setBooleanParameter("http.protocol.expect-continue", false); try { HttpEntity entity = null; if (null != file) { entity = createMultipartEntity("photo", file, postParams); post.setEntity(entity); } else if (null != postParams) { entity = new UrlEncodedFormEntity(postParams, HTTP.UTF_8); } post.setEntity(entity); } catch (IOException ioe) { throw new HttpException(ioe.getMessage(), ioe); } method = post; } else if (httpMethod.equalsIgnoreCase(HttpDelete.METHOD_NAME)) { method = new HttpDelete(uri); } else { method = new HttpGet(uri); } return method; } /** * 解析HTTP错误码 * * @param statusCode * @return */ private static String getCause(int statusCode) { String cause = null; switch (statusCode) { case NOT_MODIFIED: break; case BAD_REQUEST: cause = "The request was invalid. An accompanying error message will explain why. This is the status code will be returned during rate limiting."; break; case NOT_AUTHORIZED: cause = "Authentication credentials were missing or incorrect."; break; case FORBIDDEN: cause = "The request is understood, but it has been refused. An accompanying error message will explain why."; break; case NOT_FOUND: cause = "The URI requested is invalid or the resource requested, such as a user, does not exists."; break; case NOT_ACCEPTABLE: cause = "Returned by the Search API when an invalid format is specified in the request."; break; case INTERNAL_SERVER_ERROR: cause = "Something is broken. Please post to the group so the Weibo team can investigate."; break; case BAD_GATEWAY: cause = "Weibo is down or being upgraded."; break; case SERVICE_UNAVAILABLE: cause = "Service Unavailable: The Weibo servers are up, but overloaded with requests. Try again later. The search and trend methods use this to indicate when you are being rate limited."; break; default: cause = ""; } return statusCode + ":" + cause; } public boolean isAuthenticationEnabled() { return isAuthenticationEnabled; } public static void log(String msg) { if (DEBUG) { Log.d(TAG, msg); } } /** * Handle Status code * * @param statusCode * 响应的状态码 * @param res * 服务器响应 * @throws HttpException * 当响应码不为200时都会报出此异常:<br /> * <li>HttpRequestException, 通常发生在请求的错误,如请求错误了 网址导致404等, 抛出此异常, * 首先检查request log, 确认不是人为错误导致请求失败</li> * <li>HttpAuthException, 通常发生在Auth失败, 检查用于验证登录的用户名/密码/KEY等</li> * <li>HttpRefusedException, 通常发生在服务器接受到请求, 但拒绝请求, 可是多种原因, 具体原因 * 服务器会返回拒绝理由, 调用HttpRefusedException#getError#getMessage查看</li> * <li>HttpServerException, 通常发生在服务器发生错误时, 检查服务器端是否在正常提供服务</li> * <li>HttpException, 其他未知错误.</li> */ private void HandleResponseStatusCode(int statusCode, Response res) throws HttpException { String msg = getCause(statusCode) + "\n"; RefuseError error = null; switch (statusCode) { // It's OK, do nothing case OK: break; // Mine mistake, Check the Log case NOT_MODIFIED: case BAD_REQUEST: case NOT_FOUND: case NOT_ACCEPTABLE: throw new HttpException(msg + res.asString(), statusCode); // UserName/Password incorrect case NOT_AUTHORIZED: throw new HttpAuthException(msg + res.asString(), statusCode); // Server will return a error message, use // HttpRefusedException#getError() to see. case FORBIDDEN: throw new HttpRefusedException(msg, statusCode); // Something wrong with server case INTERNAL_SERVER_ERROR: case BAD_GATEWAY: case SERVICE_UNAVAILABLE: throw new HttpServerException(msg, statusCode); // Others default: throw new HttpException(msg + res.asString(), statusCode); } } public static String encode(String value) throws HttpException { try { return URLEncoder.encode(value, HTTP.UTF_8); } catch (UnsupportedEncodingException e_e) { throw new HttpException(e_e.getMessage(), e_e); } } public static String encodeParameters(ArrayList<BasicNameValuePair> params) throws HttpException { StringBuffer buf = new StringBuffer(); for (int j = 0; j < params.size(); j++) { if (j != 0) { buf.append("&"); } try { buf.append(URLEncoder.encode(params.get(j).getName(), "UTF-8")) .append("=") .append(URLEncoder.encode(params.get(j).getValue(), "UTF-8")); } catch (java.io.UnsupportedEncodingException neverHappen) { throw new HttpException(neverHappen.getMessage(), neverHappen); } } return buf.toString(); } /** * 异常自动恢复处理, 使用HttpRequestRetryHandler接口实现请求的异常恢复 */ private static HttpRequestRetryHandler requestRetryHandler = new HttpRequestRetryHandler() { // 自定义的恢复策略 public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { // 设置恢复策略,在发生异常时候将自动重试N次 if (executionCount >= RETRIED_TIME) { // Do not retry if over max retry count return false; } if (exception instanceof NoHttpResponseException) { // Retry if the server dropped connection on us return true; } if (exception instanceof SSLHandshakeException) { // Do not retry on SSL handshake exception return false; } HttpRequest request = (HttpRequest) context .getAttribute(ExecutionContext.HTTP_REQUEST); boolean idempotent = (request instanceof HttpEntityEnclosingRequest); if (!idempotent) { // Retry if the request is considered idempotent return true; } return false; } }; }
Java
package com.ch_linghu.fanfoudroid.http; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Document; import org.xml.sax.SAXException; import android.util.Log; import com.ch_linghu.fanfoudroid.weibo.Configuration; public class Response { // private final static String TAG = "HttpClient"; private final static String TAG = "Response"; private final static boolean DEBUG = Configuration.getDebug(); private static ThreadLocal<DocumentBuilder> builders = new ThreadLocal<DocumentBuilder>() { @Override protected DocumentBuilder initialValue() { try { return DocumentBuilderFactory.newInstance() .newDocumentBuilder(); } catch (ParserConfigurationException ex) { throw new ExceptionInInitializerError(ex); } } }; private int statusCode; private Document responseAsDocument = null; private String responseAsString = null; private InputStream is; private HttpURLConnection con; private boolean streamConsumed = false; private HttpResponse response; private StatusLine statusLine; private Header[] responseHeader; private String contentEncoding; public Response() { } public Response(HttpResponse response) throws IOException { this.response = response; this.statusLine = response.getStatusLine(); this.statusCode = statusLine.getStatusCode(); this.responseHeader = response.getAllHeaders(); HttpEntity entity = response.getEntity(); this.is = entity.getContent(); Header contentEncoding = entity.getContentEncoding(); if (null != is && contentEncoding != null && "gzip".equals(contentEncoding.getValue())) { // the response is gzipped is = new GZIPInputStream(is); } } // for test purpose /*package*/ Response(String content) { this.responseAsString = content; } public int getStatusCode() { return statusCode; } public String getResponseHeader(String name) { if (response != null) { Header[] header = response.getHeaders(name); if (header.length > 0) { return header[0].getValue(); } } return null; // return con.getHeaderField(name); } /** * Returns the response stream.<br> * This method cannot be called after calling asString() or asDcoument()<br> * It is suggested to call disconnect() after consuming the stream. * * Disconnects the internal HttpURLConnection silently. * @return response body stream * @throws HttpException * @see #disconnect() */ public InputStream asStream() { if(streamConsumed){ throw new IllegalStateException("Stream has already been consumed."); } return is; } /** * Returns the response body as string.<br> * Disconnects the internal HttpURLConnection silently. * @return response body * @throws HttpException */ public String asString() throws ResponseException { if(null == responseAsString){ BufferedReader br; try { InputStream stream = asStream(); if (null == stream) { return null; } br = new BufferedReader(new InputStreamReader(stream, "UTF-8")); StringBuffer buf = new StringBuffer(); String line; while (null != (line = br.readLine())) { buf.append(line).append("\n"); } this.responseAsString = buf.toString(); this.responseAsString = unescape(responseAsString); // log(responseAsString); stream.close(); streamConsumed = true; } catch (NullPointerException npe) { // don't remember in which case npe can be thrown throw new ResponseException(npe.getMessage(), npe); } catch (IOException ioe) { throw new ResponseException(ioe.getMessage(), ioe); } } return responseAsString; } /** * Returns the response body as org.w3c.dom.Document.<br> * Disconnects the internal HttpURLConnection silently. * @return response body as org.w3c.dom.Document * @throws HttpException */ public Document asDocument() throws ResponseException { if (null == responseAsDocument) { try { // it should be faster to read the inputstream directly. // but makes it difficult to troubleshoot this.responseAsDocument = builders.get().parse(new ByteArrayInputStream(asString().getBytes("UTF-8"))); } catch (SAXException saxe) { throw new ResponseException("The response body was not well-formed:\n" + responseAsString, saxe); } catch (IOException ioe) { throw new ResponseException("There's something with the connection.", ioe); } } return responseAsDocument; } /** * Returns the response body as sinat4j.org.json.JSONObject.<br> * Disconnects the internal HttpURLConnection silently. * @return response body as sinat4j.org.json.JSONObject * @throws HttpException */ public JSONObject asJSONObject() throws ResponseException { try { return new JSONObject(asString()); } catch (JSONException jsone) { throw new ResponseException(jsone.getMessage() + ":" + this.responseAsString, jsone); } } /** * Returns the response body as sinat4j.org.json.JSONArray.<br> * Disconnects the internal HttpURLConnection silently. * @return response body as sinat4j.org.json.JSONArray * @throws HttpException */ public JSONArray asJSONArray() throws ResponseException { try { return new JSONArray(asString()); } catch (Exception jsone) { throw new ResponseException(jsone.getMessage() + ":" + this.responseAsString, jsone); } } public InputStreamReader asReader() { try { return new InputStreamReader(is, "UTF-8"); } catch (java.io.UnsupportedEncodingException uee) { return new InputStreamReader(is); } } public void disconnect(){ con.disconnect(); } private static Pattern escaped = Pattern.compile("&#([0-9]{3,5});"); /** * Unescape UTF-8 escaped characters to string. * @author pengjianq...@gmail.com * * @param original The string to be unescaped. * @return The unescaped string */ public static String unescape(String original) { Matcher mm = escaped.matcher(original); StringBuffer unescaped = new StringBuffer(); while (mm.find()) { mm.appendReplacement(unescaped, Character.toString( (char) Integer.parseInt(mm.group(1), 10))); } mm.appendTail(unescaped); return unescaped.toString(); } @Override public String toString() { return "Response [statusCode=" + statusCode + ", responseAsDocument=" + responseAsDocument + ", responseAsString=" + responseAsString + ", is=" + is + ", con=" + con + ", streamConsumed=" + streamConsumed + ", response=" + response + ", statusLine=" + statusLine + ", responseHeader=" + Arrays.toString(responseHeader) + "]"; } private void log(String message) { if (DEBUG) { // System.out.println("[" + new java.util.Date() + "]" + message); Log.i(TAG, message); } } private void log(String message, String message2) { if (DEBUG) { log(message + message2); } } public String getResponseAsString() { return responseAsString; } public void setResponseAsString(String responseAsString) { this.responseAsString = responseAsString; } public void setStatusCode(int statusCode) { this.statusCode = statusCode; } }
Java
package com.ch_linghu.fanfoudroid.http; import java.util.HashMap; import java.util.Map; public class HTMLEntity { public static String escape(String original) { StringBuffer buf = new StringBuffer(original); escape(buf); return buf.toString(); } public static void escape(StringBuffer original) { int index = 0; String escaped; while (index < original.length()) { escaped = entityEscapeMap.get(original.substring(index, index + 1)); if (null != escaped) { original.replace(index, index + 1, escaped); index += escaped.length(); } else { index++; } } } public static String unescape(String original) { StringBuffer buf = new StringBuffer(original); unescape(buf); return buf.toString(); } public static void unescape(StringBuffer original) { int index = 0; int semicolonIndex = 0; String escaped; String entity; while (index < original.length()) { index = original.indexOf("&", index); if (-1 == index) { break; } semicolonIndex = original.indexOf(";", index); if (-1 != semicolonIndex && 10 > (semicolonIndex - index)) { escaped = original.substring(index, semicolonIndex + 1); entity = escapeEntityMap.get(escaped); if (null != entity) { original.replace(index, semicolonIndex + 1, entity); } index++; } else { break; } } } private static Map<String, String> entityEscapeMap = new HashMap<String, String>(); private static Map<String, String> escapeEntityMap = new HashMap<String, String>(); static { String[][] entities = {{"&nbsp;", "&#160;"/* no-break space = non-breaking space */, "\u00A0"} , {"&iexcl;", "&#161;"/* inverted exclamation mark */, "\u00A1"} , {"&cent;", "&#162;"/* cent sign */, "\u00A2"} , {"&pound;", "&#163;"/* pound sign */, "\u00A3"} , {"&curren;", "&#164;"/* currency sign */, "\u00A4"} , {"&yen;", "&#165;"/* yen sign = yuan sign */, "\u00A5"} , {"&brvbar;", "&#166;"/* broken bar = broken vertical bar */, "\u00A6"} , {"&sect;", "&#167;"/* section sign */, "\u00A7"} , {"&uml;", "&#168;"/* diaeresis = spacing diaeresis */, "\u00A8"} , {"&copy;", "&#169;"/* copyright sign */, "\u00A9"} , {"&ordf;", "&#170;"/* feminine ordinal indicator */, "\u00AA"} , {"&laquo;", "&#171;"/* left-pointing double angle quotation mark = left pointing guillemet */, "\u00AB"} , {"&not;", "&#172;"/* not sign = discretionary hyphen */, "\u00AC"} , {"&shy;", "&#173;"/* soft hyphen = discretionary hyphen */, "\u00AD"} , {"&reg;", "&#174;"/* registered sign = registered trade mark sign */, "\u00AE"} , {"&macr;", "&#175;"/* macron = spacing macron = overline = APL overbar */, "\u00AF"} , {"&deg;", "&#176;"/* degree sign */, "\u00B0"} , {"&plusmn;", "&#177;"/* plus-minus sign = plus-or-minus sign */, "\u00B1"} , {"&sup2;", "&#178;"/* superscript two = superscript digit two = squared */, "\u00B2"} , {"&sup3;", "&#179;"/* superscript three = superscript digit three = cubed */, "\u00B3"} , {"&acute;", "&#180;"/* acute accent = spacing acute */, "\u00B4"} , {"&micro;", "&#181;"/* micro sign */, "\u00B5"} , {"&para;", "&#182;"/* pilcrow sign = paragraph sign */, "\u00B6"} , {"&middot;", "&#183;"/* middle dot = Georgian comma = Greek middle dot */, "\u00B7"} , {"&cedil;", "&#184;"/* cedilla = spacing cedilla */, "\u00B8"} , {"&sup1;", "&#185;"/* superscript one = superscript digit one */, "\u00B9"} , {"&ordm;", "&#186;"/* masculine ordinal indicator */, "\u00BA"} , {"&raquo;", "&#187;"/* right-pointing double angle quotation mark = right pointing guillemet */, "\u00BB"} , {"&frac14;", "&#188;"/* vulgar fraction one quarter = fraction one quarter */, "\u00BC"} , {"&frac12;", "&#189;"/* vulgar fraction one half = fraction one half */, "\u00BD"} , {"&frac34;", "&#190;"/* vulgar fraction three quarters = fraction three quarters */, "\u00BE"} , {"&iquest;", "&#191;"/* inverted question mark = turned question mark */, "\u00BF"} , {"&Agrave;", "&#192;"/* latin capital letter A with grave = latin capital letter A grave */, "\u00C0"} , {"&Aacute;", "&#193;"/* latin capital letter A with acute */, "\u00C1"} , {"&Acirc;", "&#194;"/* latin capital letter A with circumflex */, "\u00C2"} , {"&Atilde;", "&#195;"/* latin capital letter A with tilde */, "\u00C3"} , {"&Auml;", "&#196;"/* latin capital letter A with diaeresis */, "\u00C4"} , {"&Aring;", "&#197;"/* latin capital letter A with ring above = latin capital letter A ring */, "\u00C5"} , {"&AElig;", "&#198;"/* latin capital letter AE = latin capital ligature AE */, "\u00C6"} , {"&Ccedil;", "&#199;"/* latin capital letter C with cedilla */, "\u00C7"} , {"&Egrave;", "&#200;"/* latin capital letter E with grave */, "\u00C8"} , {"&Eacute;", "&#201;"/* latin capital letter E with acute */, "\u00C9"} , {"&Ecirc;", "&#202;"/* latin capital letter E with circumflex */, "\u00CA"} , {"&Euml;", "&#203;"/* latin capital letter E with diaeresis */, "\u00CB"} , {"&Igrave;", "&#204;"/* latin capital letter I with grave */, "\u00CC"} , {"&Iacute;", "&#205;"/* latin capital letter I with acute */, "\u00CD"} , {"&Icirc;", "&#206;"/* latin capital letter I with circumflex */, "\u00CE"} , {"&Iuml;", "&#207;"/* latin capital letter I with diaeresis */, "\u00CF"} , {"&ETH;", "&#208;"/* latin capital letter ETH */, "\u00D0"} , {"&Ntilde;", "&#209;"/* latin capital letter N with tilde */, "\u00D1"} , {"&Ograve;", "&#210;"/* latin capital letter O with grave */, "\u00D2"} , {"&Oacute;", "&#211;"/* latin capital letter O with acute */, "\u00D3"} , {"&Ocirc;", "&#212;"/* latin capital letter O with circumflex */, "\u00D4"} , {"&Otilde;", "&#213;"/* latin capital letter O with tilde */, "\u00D5"} , {"&Ouml;", "&#214;"/* latin capital letter O with diaeresis */, "\u00D6"} , {"&times;", "&#215;"/* multiplication sign */, "\u00D7"} , {"&Oslash;", "&#216;"/* latin capital letter O with stroke = latin capital letter O slash */, "\u00D8"} , {"&Ugrave;", "&#217;"/* latin capital letter U with grave */, "\u00D9"} , {"&Uacute;", "&#218;"/* latin capital letter U with acute */, "\u00DA"} , {"&Ucirc;", "&#219;"/* latin capital letter U with circumflex */, "\u00DB"} , {"&Uuml;", "&#220;"/* latin capital letter U with diaeresis */, "\u00DC"} , {"&Yacute;", "&#221;"/* latin capital letter Y with acute */, "\u00DD"} , {"&THORN;", "&#222;"/* latin capital letter THORN */, "\u00DE"} , {"&szlig;", "&#223;"/* latin small letter sharp s = ess-zed */, "\u00DF"} , {"&agrave;", "&#224;"/* latin small letter a with grave = latin small letter a grave */, "\u00E0"} , {"&aacute;", "&#225;"/* latin small letter a with acute */, "\u00E1"} , {"&acirc;", "&#226;"/* latin small letter a with circumflex */, "\u00E2"} , {"&atilde;", "&#227;"/* latin small letter a with tilde */, "\u00E3"} , {"&auml;", "&#228;"/* latin small letter a with diaeresis */, "\u00E4"} , {"&aring;", "&#229;"/* latin small letter a with ring above = latin small letter a ring */, "\u00E5"} , {"&aelig;", "&#230;"/* latin small letter ae = latin small ligature ae */, "\u00E6"} , {"&ccedil;", "&#231;"/* latin small letter c with cedilla */, "\u00E7"} , {"&egrave;", "&#232;"/* latin small letter e with grave */, "\u00E8"} , {"&eacute;", "&#233;"/* latin small letter e with acute */, "\u00E9"} , {"&ecirc;", "&#234;"/* latin small letter e with circumflex */, "\u00EA"} , {"&euml;", "&#235;"/* latin small letter e with diaeresis */, "\u00EB"} , {"&igrave;", "&#236;"/* latin small letter i with grave */, "\u00EC"} , {"&iacute;", "&#237;"/* latin small letter i with acute */, "\u00ED"} , {"&icirc;", "&#238;"/* latin small letter i with circumflex */, "\u00EE"} , {"&iuml;", "&#239;"/* latin small letter i with diaeresis */, "\u00EF"} , {"&eth;", "&#240;"/* latin small letter eth */, "\u00F0"} , {"&ntilde;", "&#241;"/* latin small letter n with tilde */, "\u00F1"} , {"&ograve;", "&#242;"/* latin small letter o with grave */, "\u00F2"} , {"&oacute;", "&#243;"/* latin small letter o with acute */, "\u00F3"} , {"&ocirc;", "&#244;"/* latin small letter o with circumflex */, "\u00F4"} , {"&otilde;", "&#245;"/* latin small letter o with tilde */, "\u00F5"} , {"&ouml;", "&#246;"/* latin small letter o with diaeresis */, "\u00F6"} , {"&divide;", "&#247;"/* division sign */, "\u00F7"} , {"&oslash;", "&#248;"/* latin small letter o with stroke = latin small letter o slash */, "\u00F8"} , {"&ugrave;", "&#249;"/* latin small letter u with grave */, "\u00F9"} , {"&uacute;", "&#250;"/* latin small letter u with acute */, "\u00FA"} , {"&ucirc;", "&#251;"/* latin small letter u with circumflex */, "\u00FB"} , {"&uuml;", "&#252;"/* latin small letter u with diaeresis */, "\u00FC"} , {"&yacute;", "&#253;"/* latin small letter y with acute */, "\u00FD"} , {"&thorn;", "&#254;"/* latin small letter thorn with */, "\u00FE"} , {"&yuml;", "&#255;"/* latin small letter y with diaeresis */, "\u00FF"} , {"&fnof;", "&#402;"/* latin small f with hook = function = florin */, "\u0192"} /* Greek */ , {"&Alpha;", "&#913;"/* greek capital letter alpha */, "\u0391"} , {"&Beta;", "&#914;"/* greek capital letter beta */, "\u0392"} , {"&Gamma;", "&#915;"/* greek capital letter gamma */, "\u0393"} , {"&Delta;", "&#916;"/* greek capital letter delta */, "\u0394"} , {"&Epsilon;", "&#917;"/* greek capital letter epsilon */, "\u0395"} , {"&Zeta;", "&#918;"/* greek capital letter zeta */, "\u0396"} , {"&Eta;", "&#919;"/* greek capital letter eta */, "\u0397"} , {"&Theta;", "&#920;"/* greek capital letter theta */, "\u0398"} , {"&Iota;", "&#921;"/* greek capital letter iota */, "\u0399"} , {"&Kappa;", "&#922;"/* greek capital letter kappa */, "\u039A"} , {"&Lambda;", "&#923;"/* greek capital letter lambda */, "\u039B"} , {"&Mu;", "&#924;"/* greek capital letter mu */, "\u039C"} , {"&Nu;", "&#925;"/* greek capital letter nu */, "\u039D"} , {"&Xi;", "&#926;"/* greek capital letter xi */, "\u039E"} , {"&Omicron;", "&#927;"/* greek capital letter omicron */, "\u039F"} , {"&Pi;", "&#928;"/* greek capital letter pi */, "\u03A0"} , {"&Rho;", "&#929;"/* greek capital letter rho */, "\u03A1"} /* there is no Sigmaf and no \u03A2 */ , {"&Sigma;", "&#931;"/* greek capital letter sigma */, "\u03A3"} , {"&Tau;", "&#932;"/* greek capital letter tau */, "\u03A4"} , {"&Upsilon;", "&#933;"/* greek capital letter upsilon */, "\u03A5"} , {"&Phi;", "&#934;"/* greek capital letter phi */, "\u03A6"} , {"&Chi;", "&#935;"/* greek capital letter chi */, "\u03A7"} , {"&Psi;", "&#936;"/* greek capital letter psi */, "\u03A8"} , {"&Omega;", "&#937;"/* greek capital letter omega */, "\u03A9"} , {"&alpha;", "&#945;"/* greek small letter alpha */, "\u03B1"} , {"&beta;", "&#946;"/* greek small letter beta */, "\u03B2"} , {"&gamma;", "&#947;"/* greek small letter gamma */, "\u03B3"} , {"&delta;", "&#948;"/* greek small letter delta */, "\u03B4"} , {"&epsilon;", "&#949;"/* greek small letter epsilon */, "\u03B5"} , {"&zeta;", "&#950;"/* greek small letter zeta */, "\u03B6"} , {"&eta;", "&#951;"/* greek small letter eta */, "\u03B7"} , {"&theta;", "&#952;"/* greek small letter theta */, "\u03B8"} , {"&iota;", "&#953;"/* greek small letter iota */, "\u03B9"} , {"&kappa;", "&#954;"/* greek small letter kappa */, "\u03BA"} , {"&lambda;", "&#955;"/* greek small letter lambda */, "\u03BB"} , {"&mu;", "&#956;"/* greek small letter mu */, "\u03BC"} , {"&nu;", "&#957;"/* greek small letter nu */, "\u03BD"} , {"&xi;", "&#958;"/* greek small letter xi */, "\u03BE"} , {"&omicron;", "&#959;"/* greek small letter omicron */, "\u03BF"} , {"&pi;", "&#960;"/* greek small letter pi */, "\u03C0"} , {"&rho;", "&#961;"/* greek small letter rho */, "\u03C1"} , {"&sigmaf;", "&#962;"/* greek small letter final sigma */, "\u03C2"} , {"&sigma;", "&#963;"/* greek small letter sigma */, "\u03C3"} , {"&tau;", "&#964;"/* greek small letter tau */, "\u03C4"} , {"&upsilon;", "&#965;"/* greek small letter upsilon */, "\u03C5"} , {"&phi;", "&#966;"/* greek small letter phi */, "\u03C6"} , {"&chi;", "&#967;"/* greek small letter chi */, "\u03C7"} , {"&psi;", "&#968;"/* greek small letter psi */, "\u03C8"} , {"&omega;", "&#969;"/* greek small letter omega */, "\u03C9"} , {"&thetasym;", "&#977;"/* greek small letter theta symbol */, "\u03D1"} , {"&upsih;", "&#978;"/* greek upsilon with hook symbol */, "\u03D2"} , {"&piv;", "&#982;"/* greek pi symbol */, "\u03D6"} /* General Punctuation */ , {"&bull;", "&#8226;"/* bullet = black small circle */, "\u2022"} /* bullet is NOT the same as bullet operator ,"\u2219*/ , {"&hellip;", "&#8230;"/* horizontal ellipsis = three dot leader */, "\u2026"} , {"&prime;", "&#8242;"/* prime = minutes = feet */, "\u2032"} , {"&Prime;", "&#8243;"/* double prime = seconds = inches */, "\u2033"} , {"&oline;", "&#8254;"/* overline = spacing overscore */, "\u203E"} , {"&frasl;", "&#8260;"/* fraction slash */, "\u2044"} /* Letterlike Symbols */ , {"&weierp;", "&#8472;"/* script capital P = power set = Weierstrass p */, "\u2118"} , {"&image;", "&#8465;"/* blackletter capital I = imaginary part */, "\u2111"} , {"&real;", "&#8476;"/* blackletter capital R = real part symbol */, "\u211C"} , {"&trade;", "&#8482;"/* trade mark sign */, "\u2122"} , {"&alefsym;", "&#8501;"/* alef symbol = first transfinite cardinal */, "\u2135"} /* alef symbol is NOT the same as hebrew letter alef ,"\u05D0"}*/ /* Arrows */ , {"&larr;", "&#8592;"/* leftwards arrow */, "\u2190"} , {"&uarr;", "&#8593;"/* upwards arrow */, "\u2191"} , {"&rarr;", "&#8594;"/* rightwards arrow */, "\u2192"} , {"&darr;", "&#8595;"/* downwards arrow */, "\u2193"} , {"&harr;", "&#8596;"/* left right arrow */, "\u2194"} , {"&crarr;", "&#8629;"/* downwards arrow with corner leftwards = carriage return */, "\u21B5"} , {"&lArr;", "&#8656;"/* leftwards double arrow */, "\u21D0"} /* Unicode does not say that lArr is the same as the 'is implied by' arrow but also does not have any other character for that function. So ? lArr can be used for 'is implied by' as ISOtech suggests */ , {"&uArr;", "&#8657;"/* upwards double arrow */, "\u21D1"} , {"&rArr;", "&#8658;"/* rightwards double arrow */, "\u21D2"} /* Unicode does not say this is the 'implies' character but does not have another character with this function so ? rArr can be used for 'implies' as ISOtech suggests */ , {"&dArr;", "&#8659;"/* downwards double arrow */, "\u21D3"} , {"&hArr;", "&#8660;"/* left right double arrow */, "\u21D4"} /* Mathematical Operators */ , {"&forall;", "&#8704;"/* for all */, "\u2200"} , {"&part;", "&#8706;"/* partial differential */, "\u2202"} , {"&exist;", "&#8707;"/* there exists */, "\u2203"} , {"&empty;", "&#8709;"/* empty set = null set = diameter */, "\u2205"} , {"&nabla;", "&#8711;"/* nabla = backward difference */, "\u2207"} , {"&isin;", "&#8712;"/* element of */, "\u2208"} , {"&notin;", "&#8713;"/* not an element of */, "\u2209"} , {"&ni;", "&#8715;"/* contains as member */, "\u220B"} /* should there be a more memorable name than 'ni'? */ , {"&prod;", "&#8719;"/* n-ary product = product sign */, "\u220F"} /* prod is NOT the same character as ,"\u03A0"}*/ , {"&sum;", "&#8721;"/* n-ary sumation */, "\u2211"} /* sum is NOT the same character as ,"\u03A3"}*/ , {"&minus;", "&#8722;"/* minus sign */, "\u2212"} , {"&lowast;", "&#8727;"/* asterisk operator */, "\u2217"} , {"&radic;", "&#8730;"/* square root = radical sign */, "\u221A"} , {"&prop;", "&#8733;"/* proportional to */, "\u221D"} , {"&infin;", "&#8734;"/* infinity */, "\u221E"} , {"&ang;", "&#8736;"/* angle */, "\u2220"} , {"&and;", "&#8743;"/* logical and = wedge */, "\u2227"} , {"&or;", "&#8744;"/* logical or = vee */, "\u2228"} , {"&cap;", "&#8745;"/* intersection = cap */, "\u2229"} , {"&cup;", "&#8746;"/* union = cup */, "\u222A"} , {"&int;", "&#8747;"/* integral */, "\u222B"} , {"&there4;", "&#8756;"/* therefore */, "\u2234"} , {"&sim;", "&#8764;"/* tilde operator = varies with = similar to */, "\u223C"} /* tilde operator is NOT the same character as the tilde ,"\u007E"}*/ , {"&cong;", "&#8773;"/* approximately equal to */, "\u2245"} , {"&asymp;", "&#8776;"/* almost equal to = asymptotic to */, "\u2248"} , {"&ne;", "&#8800;"/* not equal to */, "\u2260"} , {"&equiv;", "&#8801;"/* identical to */, "\u2261"} , {"&le;", "&#8804;"/* less-than or equal to */, "\u2264"} , {"&ge;", "&#8805;"/* greater-than or equal to */, "\u2265"} , {"&sub;", "&#8834;"/* subset of */, "\u2282"} , {"&sup;", "&#8835;"/* superset of */, "\u2283"} /* note that nsup 'not a superset of ,"\u2283"}*/ , {"&sube;", "&#8838;"/* subset of or equal to */, "\u2286"} , {"&supe;", "&#8839;"/* superset of or equal to */, "\u2287"} , {"&oplus;", "&#8853;"/* circled plus = direct sum */, "\u2295"} , {"&otimes;", "&#8855;"/* circled times = vector product */, "\u2297"} , {"&perp;", "&#8869;"/* up tack = orthogonal to = perpendicular */, "\u22A5"} , {"&sdot;", "&#8901;"/* dot operator */, "\u22C5"} /* dot operator is NOT the same character as ,"\u00B7"} /* Miscellaneous Technical */ , {"&lceil;", "&#8968;"/* left ceiling = apl upstile */, "\u2308"} , {"&rceil;", "&#8969;"/* right ceiling */, "\u2309"} , {"&lfloor;", "&#8970;"/* left floor = apl downstile */, "\u230A"} , {"&rfloor;", "&#8971;"/* right floor */, "\u230B"} , {"&lang;", "&#9001;"/* left-pointing angle bracket = bra */, "\u2329"} /* lang is NOT the same character as ,"\u003C"}*/ , {"&rang;", "&#9002;"/* right-pointing angle bracket = ket */, "\u232A"} /* rang is NOT the same character as ,"\u003E"}*/ /* Geometric Shapes */ , {"&loz;", "&#9674;"/* lozenge */, "\u25CA"} /* Miscellaneous Symbols */ , {"&spades;", "&#9824;"/* black spade suit */, "\u2660"} /* black here seems to mean filled as opposed to hollow */ , {"&clubs;", "&#9827;"/* black club suit = shamrock */, "\u2663"} , {"&hearts;", "&#9829;"/* black heart suit = valentine */, "\u2665"} , {"&diams;", "&#9830;"/* black diamond suit */, "\u2666"} , {"&quot;", "&#34;" /* quotation mark = APL quote */, "\""} , {"&amp;", "&#38;" /* ampersand */, "\u0026"} , {"&lt;", "&#60;" /* less-than sign */, "\u003C"} , {"&gt;", "&#62;" /* greater-than sign */, "\u003E"} /* Latin Extended-A */ , {"&OElig;", "&#338;" /* latin capital ligature OE */, "\u0152"} , {"&oelig;", "&#339;" /* latin small ligature oe */, "\u0153"} /* ligature is a misnomer this is a separate character in some languages */ , {"&Scaron;", "&#352;" /* latin capital letter S with caron */, "\u0160"} , {"&scaron;", "&#353;" /* latin small letter s with caron */, "\u0161"} , {"&Yuml;", "&#376;" /* latin capital letter Y with diaeresis */, "\u0178"} /* Spacing Modifier Letters */ , {"&circ;", "&#710;" /* modifier letter circumflex accent */, "\u02C6"} , {"&tilde;", "&#732;" /* small tilde */, "\u02DC"} /* General Punctuation */ , {"&ensp;", "&#8194;"/* en space */, "\u2002"} , {"&emsp;", "&#8195;"/* em space */, "\u2003"} , {"&thinsp;", "&#8201;"/* thin space */, "\u2009"} , {"&zwnj;", "&#8204;"/* zero width non-joiner */, "\u200C"} , {"&zwj;", "&#8205;"/* zero width joiner */, "\u200D"} , {"&lrm;", "&#8206;"/* left-to-right mark */, "\u200E"} , {"&rlm;", "&#8207;"/* right-to-left mark */, "\u200F"} , {"&ndash;", "&#8211;"/* en dash */, "\u2013"} , {"&mdash;", "&#8212;"/* em dash */, "\u2014"} , {"&lsquo;", "&#8216;"/* left single quotation mark */, "\u2018"} , {"&rsquo;", "&#8217;"/* right single quotation mark */, "\u2019"} , {"&sbquo;", "&#8218;"/* single low-9 quotation mark */, "\u201A"} , {"&ldquo;", "&#8220;"/* left double quotation mark */, "\u201C"} , {"&rdquo;", "&#8221;"/* right double quotation mark */, "\u201D"} , {"&bdquo;", "&#8222;"/* double low-9 quotation mark */, "\u201E"} , {"&dagger;", "&#8224;"/* dagger */, "\u2020"} , {"&Dagger;", "&#8225;"/* double dagger */, "\u2021"} , {"&permil;", "&#8240;"/* per mille sign */, "\u2030"} , {"&lsaquo;", "&#8249;"/* single left-pointing angle quotation mark */, "\u2039"} /* lsaquo is proposed but not yet ISO standardized */ , {"&rsaquo;", "&#8250;"/* single right-pointing angle quotation mark */, "\u203A"} /* rsaquo is proposed but not yet ISO standardized */ , {"&euro;", "&#8364;" /* euro sign */, "\u20AC"}}; for (String[] entity : entities) { entityEscapeMap.put(entity[2], entity[0]); escapeEntityMap.put(entity[0], entity[2]); escapeEntityMap.put(entity[1], entity[2]); } } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.method.LinkMovementMethod; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.ch_linghu.fanfoudroid.helper.Preferences; import com.ch_linghu.fanfoudroid.helper.Utils; import com.ch_linghu.fanfoudroid.http.HttpAuthException; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.HttpRefusedException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.weibo.User; //登录页面需要个性化的菜单绑定, 不直接继承 BaseActivity public class LoginActivity extends Activity { private static final String TAG = "LoginActivity"; private static final String SIS_RUNNING_KEY = "running"; private String mUsername; private String mPassword; // Views. private EditText mUsernameEdit; private EditText mPasswordEdit; private TextView mProgressText; private Button mSigninButton; private ProgressDialog dialog; // Preferences. private SharedPreferences mPreferences; // Tasks. private GenericTask mLoginTask; private User user; private TaskListener mLoginTaskListener = new TaskAdapter(){ @Override public void onPreExecute(GenericTask task) { onLoginBegin(); } @Override public void onProgressUpdate(GenericTask task, Object param) { updateProgress((String)param); } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { onLoginSuccess(); } else { onLoginFailure(((LoginTask)task).getMsg()); } } @Override public String getName() { // TODO Auto-generated method stub return "Login"; } }; @Override protected void onCreate(Bundle savedInstanceState) { Log.i(TAG, "onCreate"); super.onCreate(savedInstanceState); // No Title bar requestWindowFeature(Window.FEATURE_NO_TITLE); requestWindowFeature(Window.FEATURE_PROGRESS); mPreferences = PreferenceManager.getDefaultSharedPreferences(this); setContentView(R.layout.login); // TextView中嵌入HTML链接 TextView registerLink = (TextView) findViewById(R.id.register_link); registerLink.setMovementMethod(LinkMovementMethod.getInstance()); mUsernameEdit = (EditText) findViewById(R.id.username_edit); mPasswordEdit = (EditText) findViewById(R.id.password_edit); // mUsernameEdit.setOnKeyListener(enterKeyHandler); mPasswordEdit.setOnKeyListener(enterKeyHandler); mProgressText = (TextView) findViewById(R.id.progress_text); mProgressText.setFreezesText(true); mSigninButton = (Button) findViewById(R.id.signin_button); if (savedInstanceState != null) { if (savedInstanceState.containsKey(SIS_RUNNING_KEY)) { if (savedInstanceState.getBoolean(SIS_RUNNING_KEY)) { Log.i(TAG, "Was previously logging in. Restart action."); doLogin(); } } } mSigninButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { doLogin(); } }); } @Override protected void onDestroy() { Log.i(TAG, "onDestory"); if (mLoginTask != null && mLoginTask.getStatus() == GenericTask.Status.RUNNING) { mLoginTask.cancel(true); } // dismiss dialog before destroy // to avoid android.view.WindowLeaked Exception if (dialog != null) { dialog.dismiss(); } super.onDestroy(); } @Override protected void onStop() { Log.i(TAG, "onStop"); // TODO Auto-generated method stub super.onStop(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mLoginTask != null && mLoginTask.getStatus() == GenericTask.Status.RUNNING) { // If the task was running, want to start it anew when the // Activity restarts. // This addresses the case where you user changes orientation // in the middle of execution. outState.putBoolean(SIS_RUNNING_KEY, true); } } // UI helpers. private void updateProgress(String progress) { mProgressText.setText(progress); } private void enableLogin() { mUsernameEdit.setEnabled(true); mPasswordEdit.setEnabled(true); mSigninButton.setEnabled(true); } private void disableLogin() { mUsernameEdit.setEnabled(false); mPasswordEdit.setEnabled(false); mSigninButton.setEnabled(false); } // Login task. private void doLogin() { mUsername = mUsernameEdit.getText().toString(); mPassword = mPasswordEdit.getText().toString(); if (mLoginTask != null && mLoginTask.getStatus() == GenericTask.Status.RUNNING){ return; }else{ if (!Utils.isEmpty(mUsername) & !Utils.isEmpty(mPassword) ) { mLoginTask = new LoginTask(); mLoginTask.setListener(mLoginTaskListener); TaskParams params = new TaskParams(); params.put("username", mUsername); params.put("password", mPassword); mLoginTask.execute(params); } else { updateProgress(getString(R.string.login_status_null_username_or_password)); } } } private void onLoginBegin() { disableLogin(); dialog = ProgressDialog.show(LoginActivity.this, "", getString(R.string.login_status_logging_in), true); dialog.setCancelable(true); } private void onLoginSuccess() { dialog.dismiss(); updateProgress(""); mUsernameEdit.setText(""); mPasswordEdit.setText(""); Log.i(TAG, "Storing credentials."); TwitterApplication.mApi.setCredentials(mUsername, mPassword); Intent intent = getIntent().getParcelableExtra(Intent.EXTRA_INTENT); String action = intent.getAction(); if (intent.getAction() == null || !Intent.ACTION_SEND.equals(action)) { // We only want to reuse the intent if it was photo send. // Or else default to the main activity. intent = new Intent(this, TwitterActivity.class); } startActivity(intent); finish(); } private void onLoginFailure(String reason) { Toast.makeText(this, reason, Toast.LENGTH_SHORT).show(); if (dialog != null){ dialog.dismiss(); } enableLogin(); } private class LoginTask extends GenericTask { private String msg = getString(R.string.login_status_failure); public String getMsg(){ return msg; } @Override protected TaskResult _doInBackground(TaskParams...params) { TaskParams param = params[0]; publishProgress(getString(R.string.login_status_logging_in) + "..."); try { String username = param.getString("username"); String password = param.getString("password"); user= TwitterApplication.mApi.login(username, password); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); Throwable cause = e.getCause(); // Maybe null if (cause instanceof HttpAuthException) { // Invalid userName/password msg = ((HttpRefusedException) cause).getError().getMessage(); } else { msg = getString(R.string.login_status_network_or_connection_error); } publishProgress(msg); return TaskResult.FAILED; } SharedPreferences.Editor editor = mPreferences.edit(); editor.putString(Preferences.USERNAME_KEY, mUsername); editor.putString(Preferences.PASSWORD_KEY, mPassword); //add 存储当前用户的id editor.putString(Preferences.CURRENT_USER_ID, user.getId()); editor.commit(); return TaskResult.OK; } } private View.OnKeyListener enterKeyHandler = new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { if (event.getAction() == KeyEvent.ACTION_UP) { doLogin(); } return true; } return false; } }; }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.Menu; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.data.db.StatusTable; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity; import com.ch_linghu.fanfoudroid.weibo.Paging; import com.ch_linghu.fanfoudroid.weibo.Status; //TODO: 数据来源换成 getFavorites() public class FavoritesActivity extends TwitterCursorBaseActivity { private static final String TAG = "FavoritesActivity"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FAVORITES"; private static final String USER_ID = "userid"; static final int DIALOG_WRITE_ID = 0; private String userId = null; public static Intent createIntent(String userId) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra(USER_ID, userId); return intent; } @Override protected boolean _onCreate(Bundle savedInstanceState) { if (super._onCreate(savedInstanceState)){ setHeaderTitle(getActivityTitle()); return true; }else{ return false; } } public static Intent createNewTaskIntent(String userId) { Intent intent = createIntent(userId); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); return intent; } // Menu. @Override public boolean onCreateOptionsMenu(Menu menu) { return super.onCreateOptionsMenu(menu); } @Override protected Cursor fetchMessages() { // TODO Auto-generated method stub return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_FAVORITE); } @Override protected String getActivityTitle() { // TODO Auto-generated method stub String template = getString(R.string.page_title_favorites); String who; if (getUserId().equals(TwitterApplication.getMyselfId())){ who = "我"; }else{ who = getUserId(); } return MessageFormat.format(template, who); } @Override protected void markAllRead() { // TODO Auto-generated method stub getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_FAVORITE); } // hasRetrieveListTask interface @Override public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) { return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_FAVORITE, isUnread); } @Override public String fetchMaxId() { return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_FAVORITE); } @Override public List<Status> getMessageSinceId(String maxId) throws HttpException { if (maxId != null){ return getApi().getFavorites(getUserId(), new Paging(maxId)); }else{ return getApi().getFavorites(getUserId()); } } @Override public String fetchMinId() { return getDb().fetchMinTweetId(getUserId(), StatusTable.TYPE_FAVORITE); } @Override public List<Status> getMoreMessageFromId(String minId) throws HttpException { Paging paging = new Paging(1, 20); paging.setMaxId(minId); return getApi().getFavorites(getUserId(), paging); } @Override public int getDatabaseType() { return StatusTable.TYPE_FAVORITE; } @Override public String getUserId() { Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null){ userId = extras.getString(USER_ID); } else { userId = TwitterApplication.getMyselfId(); } return userId; } }
Java
package com.ch_linghu.fanfoudroid; import java.util.ArrayList; import java.util.List; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.widget.ListView; import android.widget.TextView; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.helper.Utils; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.HttpRefusedException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.base.Refreshable; import com.ch_linghu.fanfoudroid.ui.base.TwitterListBaseActivity; import com.ch_linghu.fanfoudroid.ui.module.MyListView; import com.ch_linghu.fanfoudroid.ui.module.TweetArrayAdapter; import com.ch_linghu.fanfoudroid.weibo.Paging; import com.ch_linghu.fanfoudroid.weibo.User; public class UserTimelineActivity extends TwitterListBaseActivity implements MyListView.OnNeedMoreListener, Refreshable { private static final String TAG = UserTimelineActivity.class .getSimpleName(); private static final String EXTRA_USERID = "userID"; private static final String EXTRA_NAME_SHOW = "showName"; private static final String SIS_RUNNING_KEY = "running"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.USERTIMELINE"; public static Intent createIntent(String userID, String showName) { Intent intent = new Intent(LAUNCH_ACTION); intent.putExtra(EXTRA_USERID, userID); intent.putExtra(EXTRA_NAME_SHOW, showName); return intent; } // State. private User mUser; private String mUserID; private String mShowName; private ArrayList<Tweet> mTweets; private int mNextPage = 1; // Views. private TextView headerView; private TextView footerView; private MyListView mTweetList; // 记录服务器拒绝访问的信息 private String msg; private static final int LOADINGFLAG = 1; private static final int SUCCESSFLAG = 2; private static final int NETWORKERRORFLAG = 3; private static final int AUTHERRORFLAG = 4; private TweetArrayAdapter mAdapter; // Tasks. private GenericTask mRetrieveTask; private GenericTask mLoadMoreTask; private TaskListener mRetrieveTaskListener = new TaskAdapter() { @Override public void onPreExecute(GenericTask task) { onRetrieveBegin(); } @Override public void onPostExecute(GenericTask task, TaskResult result) { refreshButton.clearAnimation(); if (result == TaskResult.AUTH_ERROR) { updateHeader(AUTHERRORFLAG); return; } else if (result == TaskResult.OK) { updateHeader(SUCCESSFLAG); updateFooter(SUCCESSFLAG); draw(); goTop(); } else if (result == TaskResult.IO_ERROR) { updateHeader(NETWORKERRORFLAG); } } @Override public String getName() { return "UserTimelineRetrieve"; } }; private TaskListener mLoadMoreTaskListener = new TaskAdapter() { @Override public void onPreExecute(GenericTask task) { onLoadMoreBegin(); } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { refreshButton.clearAnimation(); updateFooter(SUCCESSFLAG); draw(); } } @Override public String getName() { return "UserTimelineLoadMoreTask"; } }; @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.i(TAG, "_onCreate()..."); if (super._onCreate(savedInstanceState)) { Intent intent = getIntent(); // get user id mUserID = intent.getStringExtra(EXTRA_USERID); // show username in title mShowName = intent.getStringExtra(EXTRA_NAME_SHOW); // Set header title setHeaderTitle("@" + mShowName); boolean wasRunning = Utils.isTrue(savedInstanceState, SIS_RUNNING_KEY); // 此处要求mTweets不为空,最好确保profile页面消息为0时不能进入这个页面 if (!mTweets.isEmpty() && !wasRunning) { updateHeader(SUCCESSFLAG); draw(); } else { doRetrieve(); } return true; } else { return false; } } @Override protected void onResume() { super.onResume(); checkIsLogedIn(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } @Override protected void onDestroy() { Log.i(TAG, "onDestroy."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { mRetrieveTask.cancel(true); } if (mLoadMoreTask != null && mLoadMoreTask.getStatus() == GenericTask.Status.RUNNING) { mLoadMoreTask.cancel(true); } super.onDestroy(); } private void draw() { mAdapter.refresh(mTweets); } public void goTop() { Log.i(TAG, "goTop."); mTweetList.setSelection(1); } public void doRetrieve() { Log.i(TAG, "Attempting retrieve."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mRetrieveTask = new UserTimelineRetrieveTask(); mRetrieveTask.setListener(mRetrieveTaskListener); mRetrieveTask.execute(); } } private void doLoadMore() { Log.i(TAG, "Attempting load more."); if (mLoadMoreTask != null && mLoadMoreTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mLoadMoreTask = new UserTimelineLoadMoreTask(); mLoadMoreTask.setListener(mLoadMoreTaskListener); mLoadMoreTask.execute(); } } private void onRetrieveBegin() { // 旋转刷新按钮 animRotate(refreshButton); // 更新查询状态显示 updateHeader(LOADINGFLAG); updateFooter(LOADINGFLAG); } private void onLoadMoreBegin() { // 旋转刷新按钮 animRotate(refreshButton); } private class UserTimelineRetrieveTask extends GenericTask { ArrayList<Tweet> mTweets = new ArrayList<Tweet>(); @Override protected TaskResult _doInBackground(TaskParams... params) { List<com.ch_linghu.fanfoudroid.weibo.Status> statusList; try { statusList = getApi().getUserTimeline(mUserID, new Paging(mNextPage)); mUser = getApi().showUser(mUserID); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); Throwable cause = e.getCause(); if (cause instanceof HttpRefusedException) { // AUTH ERROR msg = ((HttpRefusedException) cause).getError() .getMessage(); return TaskResult.AUTH_ERROR; } else { return TaskResult.IO_ERROR; } } for (com.ch_linghu.fanfoudroid.weibo.Status status : statusList) { if (isCancelled()) { return TaskResult.CANCELLED; } Tweet tweet; tweet = Tweet.create(status); mTweets.add(tweet); if (isCancelled()) { return TaskResult.CANCELLED; } } addTweets(mTweets); if (isCancelled()) { return TaskResult.CANCELLED; } return TaskResult.OK; } } private class UserTimelineLoadMoreTask extends GenericTask { ArrayList<Tweet> mTweets = new ArrayList<Tweet>(); @Override protected TaskResult _doInBackground(TaskParams... params) { List<com.ch_linghu.fanfoudroid.weibo.Status> statusList; try { statusList = getApi().getUserTimeline(mUserID, new Paging(mNextPage)); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); Throwable cause = e.getCause(); if (cause instanceof HttpRefusedException) { // AUTH ERROR msg = ((HttpRefusedException) cause).getError() .getMessage(); return TaskResult.AUTH_ERROR; } else { return TaskResult.IO_ERROR; } } for (com.ch_linghu.fanfoudroid.weibo.Status status : statusList) { if (isCancelled()) { return TaskResult.CANCELLED; } Tweet tweet; tweet = Tweet.create(status); mTweets.add(tweet); } if (isCancelled()) { return TaskResult.CANCELLED; } addTweets(mTweets); if (isCancelled()) { return TaskResult.CANCELLED; } return TaskResult.OK; } } @Override public void needMore() { if (!isLastPage()) { doLoadMore(); } } public boolean isLastPage() { return mNextPage == -1; } private synchronized void addTweets(ArrayList<Tweet> tweets) { // do more时没有更多时 if (tweets.size() == 0) { mNextPage = -1; return; } mTweets.addAll(tweets); ++mNextPage; } @Override protected String getActivityTitle() { return "@" + mShowName; } @Override protected Tweet getContextItemTweet(int position) { if (position >= 1) { return (Tweet) mAdapter.getItem(position - 1); } else { return null; } } @Override protected int getLayoutId() { return R.layout.user_timeline; } @Override protected com.ch_linghu.fanfoudroid.ui.module.TweetAdapter getTweetAdapter() { return mAdapter; } @Override protected ListView getTweetList() { return mTweetList; } @Override protected void setupState() { mTweets = new ArrayList<Tweet>(); mAdapter = new TweetArrayAdapter(this); mTweetList = (MyListView) findViewById(R.id.tweet_list); // Add Header to ListView headerView = (TextView) TextView.inflate(this, R.layout.user_timeline_header, null); mTweetList.addHeaderView(headerView); // Add Footer to ListView footerView = (TextView) TextView.inflate(this, R.layout.user_timeline_footer, null); mTweetList.addFooterView(footerView); mTweetList.setAdapter(mAdapter); mTweetList.setOnNeedMoreListener(this); } @Override protected void updateTweet(Tweet tweet) { //该方法作用? } @Override protected boolean useBasicMenu() { return true; } private void updateHeader(int flag) { if (flag == LOADINGFLAG) { // 重新刷新页面时从第一页开始获取数据 --- phoenix mNextPage = 1; mTweets.clear(); mAdapter.refresh(mTweets); headerView.setText(getResources() .getString(R.string.search_loading)); } if (flag == SUCCESSFLAG) { headerView.setText(getResources().getString( R.string.user_query_status_success)); } if (flag == NETWORKERRORFLAG) { headerView.setText(getResources().getString( R.string.login_status_network_or_connection_error)); } if (flag == AUTHERRORFLAG) { headerView.setText(msg); } } private void updateFooter(int flag) { if (flag == LOADINGFLAG) { footerView.setText("该用户总共?条消息"); } if (flag == SUCCESSFLAG) { footerView.setText("该用户总共" + mUser.getStatusesCount() + "条消息,当前显示" + mTweets.size() + "条。"); } } }
Java
package com.ch_linghu.fanfoudroid; import java.util.ArrayList; import java.util.List; import android.database.Cursor; import android.os.Bundle; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.data.db.StatusTable; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity; import com.ch_linghu.fanfoudroid.weibo.Status; /** * 随便看看 * @author jmx * */ public class BrowseActivity extends TwitterCursorBaseActivity { private static final String TAG = "BrowseActivity"; @Override protected boolean _onCreate(Bundle savedInstanceState) { if (super._onCreate(savedInstanceState)){ setHeaderTitle(getActivityTitle()); return true; }else{ return false; } } @Override protected String getActivityTitle() { return getResources().getString(R.string.page_title_browse); } @Override public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) { return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_BROWSE, isUnread); } @Override public String fetchMaxId() { return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_BROWSE); } @Override protected Cursor fetchMessages() { return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_BROWSE); } @Override public List<Status> getMessageSinceId(String maxId) throws HttpException { return getApi().getPublicTimeline(); } @Override protected void markAllRead() { getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_BROWSE); } @Override public String fetchMinId() { //随便看看没有获取更多的功能 return null; } @Override public List<Status> getMoreMessageFromId(String minId) throws HttpException { //随便看看没有获取更多的功能 return null; } @Override public int getDatabaseType() { return StatusTable.TYPE_BROWSE; } @Override public String getUserId() { return TwitterApplication.getMyselfId(); } }
Java
package com.ch_linghu.fanfoudroid.task; import java.util.HashMap; import org.json.JSONException; import com.ch_linghu.fanfoudroid.http.HttpException; /** * 暂未使用,待观察是否今后需要此类 * @author lds * */ public class TaskParams { private HashMap<String, Object> params = null; public TaskParams() { params = new HashMap<String, Object>(); } public TaskParams(String key, Object value) { this(); put(key, value); } public void put(String key, Object value) { params.put(key, value); } public Object get(String key) { return params.get(key); } /** * Get the boolean value associated with a key. * * @param key A key string. * @return The truth. * @throws HttpException * if the value is not a Boolean or the String "true" or "false". */ public boolean getBoolean(String key) throws HttpException { Object object = get(key); if (object.equals(Boolean.FALSE) || (object instanceof String && ((String)object).equalsIgnoreCase("false"))) { return false; } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String)object).equalsIgnoreCase("true"))) { return true; } throw new HttpException(key + " is not a Boolean."); } /** * Get the double value associated with a key. * @param key A key string. * @return The numeric value. * @throws HttpException if the key is not found or * if the value is not a Number object and cannot be converted to a number. */ public double getDouble(String key) throws HttpException { Object object = get(key); try { return object instanceof Number ? ((Number)object).doubleValue() : Double.parseDouble((String)object); } catch (Exception e) { throw new HttpException(key + " is not a number."); } } /** * Get the int value associated with a key. * * @param key A key string. * @return The integer value. * @throws HttpException if the key is not found or if the value cannot * be converted to an integer. */ public int getInt(String key) throws HttpException { Object object = get(key); try { return object instanceof Number ? ((Number)object).intValue() : Integer.parseInt((String)object); } catch (Exception e) { throw new HttpException(key + " is not an int."); } } /** * Get the string associated with a key. * * @param key A key string. * @return A string which is the value. * @throws JSONException if the key is not found. */ public String getString(String key) throws HttpException { Object object = get(key); return object == null ? null : object.toString(); } /** * Determine if the JSONObject contains a specific key. * @param key A key string. * @return true if the key exists in the JSONObject. */ public boolean has(String key) { return this.params.containsKey(key); } }
Java
package com.ch_linghu.fanfoudroid.task; import android.util.Log; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.data.db.StatusTable; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.ui.base.BaseActivity; public class TweetCommonTask { public static class DeleteTask extends GenericTask{ public static final String TAG="DeleteTask"; private BaseActivity activity; public DeleteTask(BaseActivity activity){ this.activity = activity; } @Override protected TaskResult _doInBackground(TaskParams... params) { TaskParams param = params[0]; try { String id = param.getString("id"); com.ch_linghu.fanfoudroid.weibo.Status status = null; status = activity.getApi().destroyStatus(id); // 对所有相关表的对应消息都进行删除(如果存在的话) activity.getDb().deleteTweet(status.getId(), "", -1); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } return TaskResult.OK; } } public static class FavoriteTask extends GenericTask{ private static final String TAG = "FavoriteTask"; private BaseActivity activity; public static final String TYPE_ADD = "add"; public static final String TYPE_DEL = "del"; private String type; public String getType(){ return type; } public FavoriteTask(BaseActivity activity){ this.activity = activity; } @Override protected TaskResult _doInBackground(TaskParams...params){ TaskParams param = params[0]; try { String action = param.getString("action"); String id = param.getString("id"); com.ch_linghu.fanfoudroid.weibo.Status status = null; if (action.equals(TYPE_ADD)) { status = activity.getApi().createFavorite(id); activity.getDb().setFavorited(id, "true"); type = TYPE_ADD; } else { status = activity.getApi().destroyFavorite(id); activity.getDb().setFavorited(id, "false"); type = TYPE_DEL; } Tweet tweet = Tweet.create(status); // if (!Utils.isEmpty(tweet.profileImageUrl)) { // // Fetch image to cache. // try { // activity.getImageManager().put(tweet.profileImageUrl); // } catch (IOException e) { // Log.e(TAG, e.getMessage(), e); // } // } if(action.equals(TYPE_DEL)){ activity.getDb().deleteTweet(tweet.id, TwitterApplication.getMyselfId(), StatusTable.TYPE_FAVORITE); } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } return TaskResult.OK; } } // public static class UserTask extends GenericTask{ // // @Override // protected TaskResult _doInBackground(TaskParams... params) { // // TODO Auto-generated method stub // return null; // } // // } }
Java