Java tutorial
/* * Copyright (C) 2012 ukasz Wasylkowski * * 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 pl.zajecia.cw3; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.support.v4.app.NavUtils; import android.support.v4.content.LocalBroadcastManager; import android.util.SparseArray; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.GridView; import android.widget.ImageView; /** * Main class. */ public class PhotosActivity extends Activity { @SuppressWarnings("unused") private static final String TAG = "PhotosActivity"; /** Result value for adding new image intent. */ private static final int RESULT_LOAD_IMAGE = 1; /** Images gridView gallery. */ private GridView mPhotosGridView; /** The m photos adapter. */ private PhotosAdapter mPhotosAdapter; /** List of images displayed in the gallery (and then passed as list of wallpapers). */ private List<String> mPhotos; /* (non-Javadoc) * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_photos); /** Load photos from shared preferences * and parse it to List*/ mPhotos = new ArrayList<String>(); SharedPreferences settings = getSharedPreferences(MainActivity.PREFERENCES, 0); String paths = settings.getString(MainActivity.FILE_PATHS, ""); String[] pathsArray = paths.split(";"); for (String p : pathsArray) { if (p != "") { mPhotos.add(p); } } /** Show the Up button in the action bar. */ getActionBar().setDisplayHomeAsUpEnabled(true); /** Register onClickListener for displaying gallery activity */ Button addImageButton = (Button) findViewById(R.id.addImageFromGallery); addImageButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, RESULT_LOAD_IMAGE); } }); /**Set up GridView gallery */ mPhotosAdapter = new PhotosAdapter(this); mPhotosGridView = (GridView) findViewById(R.id.photosGridView); mPhotosGridView.setAdapter(mPhotosAdapter); /** set up context menu for gallery gridView */ registerForContextMenu(mPhotosGridView); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.setHeaderTitle(R.string.image_options); menu.add(Menu.NONE, 0, Menu.NONE, R.string.remove_image); } /* (non-Javadoc) * @see android.app.Activity#onContextItemSelected(android.view.MenuItem) */ @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo a = (AdapterContextMenuInfo) item.getMenuInfo(); /** If itemId == remove picture (first and only one), remove pictur * from list and refresh gallery */ if (item.getItemId() == 0) { mPhotos.remove(a.position); mPhotosAdapter.notifyDataSetChanged(); mPhotosGridView.setAdapter(mPhotosAdapter); return true; } return super.onContextItemSelected(item); } /** * PhotosAdapter handling displaying gallery */ private class PhotosAdapter extends BaseAdapter { private Context mContext; /** All views, necessary for asynchronous refreshing. */ private SparseArray<ImageView> mViews; /** * Instantiates a new photos adapter. * * @param context currect Context */ public PhotosAdapter(Context context) { mContext = context; mViews = new SparseArray<ImageView>(); } @Override public int getCount() { return mPhotos.size(); } @Override public Object getItem(int position) { return mPhotos.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { /** If convertView isn't null, it means it's already loaded somewhere in the memory * (cached or something) */ if (convertView != null) { return convertView; } /** If there's no convertView, we have to create new one */ ImageView img = new ImageView(mContext); /** Temp image until photo is loaded */ img.setImageResource(android.R.drawable.ic_menu_gallery); mViews.append(position, img); /** Asynchronously load image */ new BitmapUtils(img).execute(mPhotos.get(position)); return img; } } @Override protected void onStop() { /** Save photos currently in gallery to shared preferences */ SharedPreferences settings = getSharedPreferences(MainActivity.PREFERENCES, 0); SharedPreferences.Editor editor = settings.edit(); editor.putString(MainActivity.FILE_PATHS, getPhotos()); editor.commit(); /** Send message to update main service */ Intent intent = new Intent(MainService.MESSAGE_UPDATE_SETTINGS); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); super.onStop(); } /** * Returns list of photos from mPhotos variable as string, joined with ';' * char. */ private String getPhotos() { StringBuilder sb = new StringBuilder(); for (String p : mPhotos) { sb.append(p); sb.append(';'); } if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); } return sb.toString(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); /** Handle adding new image to gallery */ if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null) { Uri image = data.getData(); String[] filePathColumn = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(image, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String picturePath = cursor.getString(columnIndex); cursor.close(); mPhotos.add(picturePath); mPhotosAdapter.notifyDataSetChanged(); mPhotosGridView.setAdapter(mPhotosAdapter); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: /** If user pressed home button, we get back to main activity */ NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } }