Java tutorial
package com.synchophy.ui; /* * Copyright (C) 2010 Neil Davies * * 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. * * This code is base on the Android Gallery widget and was Created * by Neil Davies neild001 'at' gmail dot com to be a Coverflow widget * * @author Neil Davies */ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.os.Message; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.Gallery; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.SectionIndexer; import android.widget.Spinner; import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper; import com.synchophy.R; import com.synchophy.json.JSONRequest; import com.synchophy.json.JSONTask; import com.synchophy.json.PlayerManager; import com.synchophy.service.ImageDownloadService; import com.synchophy.ui.helper.ActivitySwipeDetector; import com.synchophy.ui.helper.BrowseViewSelectedListener; import com.synchophy.ui.helper.CoverFlow; import com.synchophy.ui.types.Album; import com.synchophy.ui.types.Artist; public class CoverFlowActivity extends BaseActivity { private static final String TAG = CoverFlowActivity.class.getSimpleName(); protected CoverFlow coverFlow; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.coverflow); Spinner browseSpinner = (Spinner) this.findViewById(R.id.browseSpinner); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, new String[] { "Covers", "Albums", "Artists" }); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); browseSpinner.setAdapter(adapter); ActivitySwipeDetector activitySwipeDetector = new ActivitySwipeDetector(this) { @Override public void onLeftToRightSwipe() { CoverFlowActivity.this.finish(); overridePendingTransition(R.anim.hold, R.anim.push_out_to_right); } @Override public void onBottomToTopSwipe() { showPlaylist(); } }; LinearLayout lowestLayout = (LinearLayout) this.findViewById(R.id.coverflowBack); lowestLayout.setOnTouchListener(activitySwipeDetector); coverFlow = (CoverFlow) findViewById(R.id.coverflow); coverFlow.setSpacing(-25); coverFlow.setSelection(4, true); coverFlow.setAnimationDuration(1000); registerForContextMenu(coverFlow); ImageAdapter coverImageAdapter = new ImageAdapter(CoverFlowActivity.this); coverFlow.setAdapter(coverImageAdapter); refresh(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); Log.e(TAG, "Config Changed"); } @Override protected void onStart() { super.onStart(); Spinner browseSpinner = (Spinner) this.findViewById(R.id.browseSpinner); browseSpinner.setOnItemSelectedListener(new BrowseViewSelectedListener(this)); } private void refresh() { new JSONTask(this, true) { @Override public void post(Message obj) throws JSONException { Log.e("CoverFlowActivity", obj.toString()); String token = JSONRequest.getToken(CoverFlowActivity.this); JSONArray images = (JSONArray) obj.obj; String[] imageGetParams = new String[images.length()]; String[] albumLabels = new String[images.length()]; String[] albumArtists = new String[images.length()]; for (int i = 0; i < images.length(); i++) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3); JSONObject imageDef = (JSONObject) images.get(i); nameValuePairs.add(new BasicNameValuePair("k", token)); nameValuePairs.add(new BasicNameValuePair("artist", imageDef.getString("artist"))); nameValuePairs.add(new BasicNameValuePair("album", imageDef.getString("album"))); nameValuePairs.add(new BasicNameValuePair("a", "view")); final String paramString = URLEncodedUtils.format(nameValuePairs, "utf-8"); imageGetParams[i] = paramString; albumLabels[i] = imageDef.getString("album"); albumArtists[i] = imageDef.getString("artist"); Intent msgIntent = new Intent(CoverFlowActivity.this, ImageDownloadService.class); msgIntent.putExtra(ImageDownloadService.IMAGE_URL, paramString); startService(msgIntent); } ImageAdapter coverImageAdapter = (ImageAdapter) coverFlow.getAdapter(); coverImageAdapter.refresh(imageGetParams, albumLabels, albumArtists); coverImageAdapter.notifyDataSetChanged(); } }.execute("image", new BasicNameValuePair("a", "list"), new BasicNameValuePair("filter", Boolean.toString(PlayerManager.isFiltering()))); } public class ImageAdapter extends BaseAdapter implements SectionIndexer { private Context context; private String[] imageGetParams = {}; private String[] albumNames = {}; private String[] albumArtists = {}; private Map<String, Integer> sectionForPositions; private String[] sections; public ImageAdapter(Context c) { context = c; } public ImageAdapter(Context c, String[] imageGetParams, String[] albumNames, String[] albumArtists) { context = c; refresh(imageGetParams, albumNames, albumArtists); initIndexer(Arrays.asList(albumArtists)); } public void refresh(String[] imageGetParams, String[] albumNames, String[] albumArtists) { this.imageGetParams = imageGetParams; this.albumNames = albumNames; this.albumArtists = albumArtists; } public void initIndexer(List<String> albumArtists) { LinkedList<String> alphaObjects = new LinkedList<String>(albumArtists); Collections.sort(alphaObjects, new Comparator<String>() { public int compare(String f1, String f2) { return f1.toUpperCase().compareTo(f2.toUpperCase()); } }); List<String> sectionList = new LinkedList<String>(); sectionForPositions = new LinkedHashMap<String, Integer>(); for (int i = 0; i < alphaObjects.size(); i++) { String object = alphaObjects.get(i); String key = getKey(object); if (!sectionForPositions.containsKey(key)) { sectionList.add(key); sectionForPositions.put(key, Integer.valueOf(i)); } } sections = sectionList.toArray(new String[sectionList.size()]); } private String getKey(String type) { String name = type.toString(); String key = name; if (name.length() >= 2) { key = key.substring(0, 2); } return key.toUpperCase(); } @Override public int getPositionForSection(int sectionInt) { String section = sections[sectionInt]; return sectionForPositions.get(section); } @Override public int getSectionForPosition(int position) { String object = albumArtists[position]; String key = getKey(object); return sectionForPositions.get(key); } @Override public String[] getSections() { return sections; } public int getCount() { return imageGetParams.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } private String getImageUrl(String queryString) { return JSONRequest.getUrl(CoverFlowActivity.this, "image") + "?" + queryString; } public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View layout = inflater.inflate(R.layout.cover_image, null); layout.setLayoutParams(new Gallery.LayoutParams(140, 140)); layout.setTag(position); ImageView i = (ImageView) layout.findViewById(R.id.albumImage); // i.setImageURI(getUri(mImageGetParams[position])); UrlImageViewHelper.setUrlDrawable(i, getImageUrl(imageGetParams[position]), R.drawable.gmpcnocover); // i.setLayoutParams(new CoverFlow.LayoutParams(130, 130)); i.setScaleType(ImageView.ScaleType.CENTER_INSIDE); if (i.getDrawable() == null) { i.setImageResource(R.drawable.gmpcnocover); } // Make sure we set anti-aliasing otherwise we get jaggies BitmapDrawable drawable = (BitmapDrawable) i.getDrawable(); drawable.setAntiAlias(true); return layout; } public String getAlbumLabel(int position) { return albumNames[position]; } public String getAlbumArtist(int position) { return albumArtists[position]; } /** * Returns the size (0.0f to 1.0f) of the views depending on the * 'offset' to the center. */ public float getScale(boolean focused, int offset) { /* Formula: 1 / (2 ^ offset) */ return Math.max(0, 1.0f / (float) Math.pow(2, Math.abs(offset))); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.add_menu, menu); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); final CoverFlow coverFlow = (CoverFlow) findViewById(R.id.coverflow); ImageAdapter adapter = (ImageAdapter) coverFlow.getAdapter(); int position = info.position; Artist artist = new Artist(adapter.getAlbumArtist(position), 0); Album album = new Album(adapter.getAlbumLabel(position), 0, artist); switch (item.getItemId()) { case R.id.addItem: album.addType(this); return true; case R.id.addItemAndPlay: album.addAndPlayType(this); return true; case R.id.tagItem: album.tag(this); return true; case R.id.tagList: album.tagList(this); return true; case R.id.downloadItem: album.download(this); return true; case R.id.editItem: album.edit(this); return true; default: return super.onContextItemSelected(item); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.clear(); menu.add(0, BrowseActivity.MAIN, 0, R.string.mainMenu).setIcon(android.R.drawable.ic_menu_revert); menu.add(0, BrowseActivity.PLAYLIST, 1, R.string.playlist).setIcon(R.drawable.ic_menu_pmix_playlist); menu.add(0, BrowseActivity.FILTER, 1, PlayerManager.isFiltering() ? R.string.stopFiltering : R.string.startFiltering) .setIcon(PlayerManager.isFiltering() ? R.drawable.ic_menu_stop : R.drawable.ic_menu_filter); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent i = null; switch (item.getItemId()) { case BrowseActivity.MAIN: i = new Intent(this, MainMenuActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); return true; case BrowseActivity.PLAYLIST: i = new Intent(this, PlaylistActivity.class); startActivityForResult(i, BrowseActivity.PLAYLIST); return true; case BrowseActivity.FILTER: PlayerManager.setFiltering(!PlayerManager.isFiltering()); refresh(); return true; } return false; } private void showPlaylist() { Intent i = new Intent(this, PlaylistActivity.class); startActivityForResult(i, MainMenuActivity.PLAYLIST); overridePendingTransition(R.anim.pull_in_from_bottom, R.anim.hold); } }