Java tutorial
/** * Copyright (C) 2012 Picon software * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package fr.eoit.activity; import android.content.BroadcastReceiver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.SimpleCursorAdapter; import android.util.TypedValue; import android.util.Xml; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.bugsense.trace.BugSenseHandler; import fr.eo.exception.DownloadException; import fr.eo.exception.ParsingException; import fr.eoit.EOITConst; import fr.eoit.R; import fr.eoit.activity.listener.GenericIntentLauncherOnClickListener; import fr.eoit.activity.listener.ParametersMiningSecOnClickListener; import fr.eoit.activity.listener.ParametersMiningSpaceOnClickListener; import fr.eoit.db.BasicAsyncQueryHandler; import fr.eoit.db.bean.Item; import fr.eoit.db.bean.Parameter; import fr.eoit.parameter.Parameters; import fr.eoit.service.updater.SkillUpdaterService; import fr.eoit.util.AndroidUrlDownloader; import fr.eoit.util.ValueCache; import fr.eoit.xml.character.CharactersXmlParser; /** * @author picon.software * */ public class ParameterActivity extends LoaderActivity<Cursor> { private SkillUpdaterBroadcastReceiver receiver; private SimpleCursorAdapter adapter; private CharactersXmlParser charactersXMLParser; private Spinner characterSpinner; private ProgressBar skillLoadingProgress; private ListView skillListView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setContentView(R.layout.parameters); setProgressBarIndeterminate(true); setProgressBarIndeterminateVisibility(true); if (Parameters.keyId <= 0) { Toast.makeText(this, R.string.parameters_not_set, Toast.LENGTH_LONG).show(); } skillLoadingProgress = (ProgressBar) findViewById(R.id.SKILL_LIST_LOADING); receiver = new SkillUpdaterBroadcastReceiver(skillLoadingProgress); refreshCharacterSpinner(); // The names of the cursor columns to display in the view, initialized to the title column String[] dataColumns = { Item.COLUMN_NAME_NAME, Parameter.COLUMN_NAME_PARAM_VALUE }; // The view IDs that will display the cursor columns, initialized to the TextView in // noteslist_item.xml int[] viewIDs = { R.id.ITEM_NAME, R.id.SKILL_LEVEL_ICON }; // Creates the backing adapter for the ListView. adapter = new SimpleCursorAdapter(this, R.layout.skillrow, null, dataColumns, viewIDs, SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); adapter.setViewBinder(new SkillListViewBinder()); skillListView = (ListView) findViewById(R.id.SKILLS_LIST); skillListView.setVisibility(View.GONE); // Sets the ListView's adapter to be the cursor adapter that was just created. skillListView.setAdapter(adapter); findViewById(R.id.location_management_layout).setOnClickListener(new GenericIntentLauncherOnClickListener( fr.eoit.db.bean.Station.CONTENT_URI, LocationManagementActivity.class, getApplicationContext())); findViewById(R.id.MINING_REGION_LAYOUT).setOnClickListener(new ParametersMiningSpaceOnClickListener(this)); findViewById(R.id.MINING_REGION_SEC_LAYOUT) .setOnClickListener(new ParametersMiningSecOnClickListener(this)); ((CheckBox) findViewById(R.id.MINING_SWITCH)).setChecked(Parameters.isMiningActive); ((CheckBox) findViewById(R.id.MINING_SWITCH)).setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { Parameters.isMiningActive = isChecked; } }); initOrRestart(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getSupportMenuInflater(); inflater.inflate(R.menu.parameters_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.API_KEY_OPTION: final Intent paramIntent = new Intent(this, ApiKeyManagementActivity.class); startActivity(paramIntent); return true; case R.id.REFRESH_SKILLS_OPTION: skillListView.setVisibility(View.GONE); skillLoadingProgress.setVisibility(View.VISIBLE); SkillUpdaterService.updateSkills(getApplicationContext()); return true; default: break; } return super.onOptionsItemSelected(item); } @Override protected void onResume() { super.onResume(); registerReceiver(receiver, new IntentFilter(SkillUpdaterService.SKILL_CHANGED_ACTION)); } @Override protected void onPause() { super.onPause(); unregisterReceiver(receiver); Parameters.saveParameters(getApplicationContext()); Toast.makeText(this, R.string.parameters_saved, Toast.LENGTH_SHORT).show(); } @Override protected Loader<Cursor> getCursorLoader(int id, Bundle args) { setProgressBarIndeterminateVisibility(true); return new CursorLoader(this, Parameter.CONTENT_SKILLS_URI, new String[] { Parameter._ID, Item.COLUMN_NAME_NAME, Parameter.COLUMN_NAME_PARAM_VALUE }, Item.COLUMN_NAME_NAME + " IS NOT NULL AND p." + Parameter.COLUMN_NAME_PARAM_VALUE + " <> '0'", null, null); } @Override public void onLoadFinished(Cursor data) { int height = data.getCount() * ((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 25, getResources().getDisplayMetrics())); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, height); skillListView.setLayoutParams(lp); skillListView.setVisibility(View.VISIBLE); adapter.swapCursor(data); setProgressBarIndeterminateVisibility(false); } @Override public void onLoaderReset(Loader<Cursor> loader) { adapter.swapCursor(null); } @Override protected void onReload() { super.onReload(); refreshCharacterSpinner(); } private void refreshCharacterSpinner() { charactersXMLParser = new CharactersXmlParser(new AndroidUrlDownloader(), Xml.newPullParser(), Parameters.keyId, Parameters.vCode); characterSpinner = (Spinner) findViewById(R.id.CHARACTER_SPINNER); if (Parameters.vCode != null && Parameters.vCode.length() > 0) { new LoadCharacterSpinnerAsyncTask().execute((Void[]) null); } else { charactersXMLParser.resetCharacterMap(); ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, new String[] { getString(R.string.all_level_v) }); adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); characterSpinner.setAdapter(adapter); characterSpinner.setOnItemSelectedListener(null); } } private class LoadCharacterSpinnerAsyncTask extends AsyncTask<Void, Void, Void> { private int errorMsgId; @Override protected void onPreExecute() { setProgressBarIndeterminateVisibility(true); } @Override protected Void doInBackground(Void... params) { try { ValueCache.put(EOITConst.BEAN_ID_PARAMETERS, EOITConst.FIELD_ID_PARAMETERS_CHARACTER_ID, EOITConst.PARAM_CHARACTER_ID_ID, charactersXMLParser .getIndexForCharacterId(getApplicationContext(), Parameters.characterId)); } catch (ParsingException e) { cancel(true); errorMsgId = R.string.api_parsing_error; BugSenseHandler.sendException(e); } catch (DownloadException e) { cancel(true); errorMsgId = R.string.api_download_error; BugSenseHandler.sendException(e); } return null; } /* (non-Javadoc) * @see android.os.AsyncTask#onCancelled() */ @Override protected void onCancelled() { Toast.makeText(getApplicationContext(), errorMsgId, Toast.LENGTH_LONG).show(); } @Override protected void onPostExecute(Void result) { try { if (!charactersXMLParser.getCharactersMap(getApplicationContext()).isEmpty()) { ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, charactersXMLParser.getCharacterNames(getApplicationContext())); adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); characterSpinner.setAdapter(adapter); characterSpinner.setOnItemSelectedListener(new CharacterSpinnerOnItemSelectedListener()); if (Parameters.characterId != 0) { characterSpinner.setSelection((int) charactersXMLParser .getIndexForCharacterId(getApplicationContext(), Parameters.characterId)); } else { skillListView.setVisibility(View.GONE); skillLoadingProgress.setVisibility(View.VISIBLE); SkillUpdaterService.updateSkills(getApplicationContext()); } } else { Toast.makeText(getApplicationContext(), R.string.no_character_found, Toast.LENGTH_LONG).show(); } } catch (ParsingException e) { Toast.makeText(getApplicationContext(), R.string.api_parsing_error, Toast.LENGTH_LONG).show(); BugSenseHandler.sendException(e); } catch (DownloadException e) { Toast.makeText(getApplicationContext(), R.string.api_download_error, Toast.LENGTH_LONG).show(); BugSenseHandler.sendException(e); } setProgressBarIndeterminateVisibility(false); } } private class CharacterSpinnerOnItemSelectedListener implements OnItemSelectedListener { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (ValueCache.hasChangedAndUpdateCache(EOITConst.BEAN_ID_PARAMETERS, EOITConst.FIELD_ID_PARAMETERS_CHARACTER_ID, EOITConst.PARAM_CHARACTER_ID_ID, id)) { try { Parameters.characterId = charactersXMLParser.getCharacterIdAtIndex(getApplicationContext(), (int) id); } catch (ParsingException e) { Toast.makeText(getApplicationContext(), R.string.api_parsing_error, Toast.LENGTH_LONG).show(); BugSenseHandler.sendException(e); } catch (DownloadException e) { Toast.makeText(getApplicationContext(), R.string.api_download_error, Toast.LENGTH_LONG).show(); BugSenseHandler.sendException(e); } ContentValues values = new ContentValues(); values.put(Parameter.COLUMN_NAME_PARAM_VALUE, Long.toString(Parameters.keyId)); new BasicAsyncQueryHandler(getContentResolver()).startUpdate(0, null, ContentUris.withAppendedId(Parameter.CONTENT_ID_URI_BASE, EOITConst.PARAM_USER_ID_ID), values, null, null); values = new ContentValues(); values.put(Parameter.COLUMN_NAME_PARAM_VALUE, Parameters.vCode); new BasicAsyncQueryHandler(getContentResolver()).startUpdate(0, null, ContentUris.withAppendedId(Parameter.CONTENT_ID_URI_BASE, EOITConst.PARAM_API_KEY_ID), values, null, null); values = new ContentValues(); values.put(Parameter.COLUMN_NAME_PARAM_VALUE, Long.toString(Parameters.characterId)); new BasicAsyncQueryHandler(getContentResolver()).startUpdate(0, null, ContentUris.withAppendedId(Parameter.CONTENT_ID_URI_BASE, EOITConst.PARAM_CHARACTER_ID_ID), values, null, null); skillListView.setVisibility(View.GONE); skillLoadingProgress.setVisibility(View.VISIBLE); SkillUpdaterService.updateSkills(getApplicationContext()); } } @Override public void onNothingSelected(AdapterView<?> parent) { } } private class SkillListViewBinder implements SimpleCursorAdapter.ViewBinder { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { int viewId = view.getId(); TextView textView; switch (viewId) { case R.id.ITEM_NAME: textView = (TextView) view; textView.setText(cursor.getString(columnIndex)); break; case R.id.SKILL_LEVEL_ICON: ImageView imageView = (ImageView) view; short level = (short) cursor.getInt(columnIndex); if (level >= 0 && level <= 5) { imageView.setImageResource(EOITConst.skillIconsResourceIds[level]); } break; } return true; } } private class SkillUpdaterBroadcastReceiver extends BroadcastReceiver { private ProgressBar progress; public SkillUpdaterBroadcastReceiver(ProgressBar progress) { super(); this.progress = progress; } @Override public void onReceive(Context context, Intent intent) { //skillCursor.requery(); adapter.notifyDataSetChanged(); progress.setVisibility(View.GONE); context.getContentResolver().notifyChange(Parameter.CONTENT_SKILLS_URI, null); } } }