How to use switch case with string resources - java

How can I use the switch case scenario with string resources rather than hard coded names? My strings are exactly the same names used for the spellings of them.
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MainListAdapter adapter = (MainListAdapter) parent.getAdapter();
Main continent = adapter.getItem(position);
if (mTwoPane) {
View rowView = view;
setItemSelected(continent, rowView);
Fragment newFragment;
switch (stringRes) {
case R.id.africa:
newFragment = new FragmentAfrica();
break;
case R.id.asia:
newFragment = new FragmentAsia();
break;
case R.id.europe:
newFragment = new FragmentEurope();
break;
default:
newFragment = new FragmentAfrica();
}
MainActivity activity = (MainActivity) view.getContext();
FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.detail_container, newFragment);
transaction.commit();
} else {
}

Switch labels (that’s the "africa" in case "africa":) must be constant expressions according to JLS § 14.12. So if you want to use switch, you’ll have to store the string resource value in a constant variable and then use that constant as the switch label.
Example (use either class constants or local constants):
class Example {
public static final String CONTINENT_EUROPE =
getResources().getString(R.string.europe); // Option 1: class constants
public static final String CONTINENT_NORTHERN_AMERICA =
getResources().getString(R.string.northernAmerica);
public void foo() {
final String continentAfrica =
getResources().getString(R.string.africa); // Option 2: local constants
final String continentAsia =
getResources().getString(R.string.asia);
switch (continent) {
// Option 1:
case continentAfrica:
newFragment = new FragmentAfrica();
break;
case continentAsia:
newFragment = new FragmentAsia();
break;
// Option 2:
case CONTINENT_EUROPE:
newFragment = new FragmentEurope();
break;
case CONTINENT_NORTHERN_AMERICA:
newFragment = new FragmentNorthernAmerica();
break;
// ...
}
}

Looks like this could work.. use integers.
public void switchFragments(int stringRes){
if (mTwoPane) {
View rowView = view;
setItemSelected(continent, rowView);
Fragment newFragment;
switch (stringRes) {
case R.id.africa:
newFragment = new FragmentAfrica();
break;
case R.id.asia:
newFragment = new FragmentAsia();
break;
case R.id.europe:
newFragment = new FragmentEurope();
break;
default:
newFragment = new FragmentAfrica();
}
MainActivity activity = (MainActivity) view.getContext();
FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.detail_container, newFragment);
transaction.commit();
}
}
Now all you have to do is call it like this
switchFragments(R.id.africa);
This will go to the case labeled R.id.africa and switch the fragment.
It will also work with different languages, because its just an ID of a resource.

I think in this scenario the simplest way is you can just use "simple if else statement" to avoid declaring extra static variables. And also to add support on locale changes.
private String[] titles;
void initialize(){
titles = new String[]{getString(R.string.europe),getString(R.string.africa)};
}
#Override
public Fragment getItem(int position) {
String title = titles[position];
if (title.equals(getString(R.string.europe))) {
return new EuropeFragment();
} else if (title.equals(getString(R.string.africa))) {
return new AfricaFragment();
} else {
return new DefaultFragment();
}
}

Just declare them as constants like this:
public static final String COUNTRY_AFRICA = "africa";
public static final String COUNTRY_ASIA = "asia";
switch (country.toLowerCase()) {
case COUNTRY_AFRICA:
newFragment = new FragmentAfrica();
break;
// etc..
This is better than hardcoding because you will be able to reuse these constants across the app.
If those are UI strings you can declare them in strings.xml

You should declare it as an enum:
public enum Continent{
africa, asia, europe
}
public Fragment getFragment(String continentKey){
Continent continent = Continent.valueOf(continentKey);
return getFragment(continent);
}
public Fragment getFragment(Continent aContinent){
Fragment newFragment;
switch(aContinent){
case asia:
newFragment = new FragmentAsia();
break;
case europe:
newFragment = new FragmentEurope();
break;
case africa: default:
newFragment = new FragmentAfrica();
break;
}
return newFragment;
}

Related

Switch case is not working with Enum in Java [duplicate]

error: an enum switch case label must be the unqualified name of an enumeration constant
error: duplicate case label
no compiling, help me!
public class CardViewStyleSetting extends ThemedSetting {
public CardViewStyleSetting(ThemedActivity activity) {
super(activity);
}
public void show() {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), getActivity().getDialogStyle());
final View dialogLayout = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_album_card_style, null);
TextView dialogTitle = dialogLayout.findViewById(R.id.dialog_card_view_style_title);
((CardView) dialogLayout.findViewById(R.id.dialog_card_view_style)).setCardBackgroundColor(getActivity().getCardBackgroundColor());
dialogTitle.setBackgroundColor(getActivity().getPrimaryColor());
final RadioGroup rGroup = dialogLayout.findViewById(R.id.radio_group_card_view_style);
final CheckBox chkShowMediaCount = dialogLayout.findViewById(R.id.show_media_count);
final CheckBox chkShowAlbumPath = dialogLayout.findViewById(R.id.show_album_path);
RadioButton rCompact = dialogLayout.findViewById(R.id.radio_card_compact);
RadioButton rFlat = dialogLayout.findViewById(R.id.radio_card_flat);
RadioButton rMaterial = dialogLayout.findViewById(R.id.radio_card_material);
chkShowMediaCount.setChecked(Prefs.showMediaCount());
chkShowAlbumPath.setChecked(Prefs.showAlbumPath());
getActivity().themeRadioButton(rCompact);
getActivity().themeRadioButton(rFlat);
getActivity().themeRadioButton(rMaterial);
getActivity().themeCheckBox(chkShowMediaCount);
getActivity().themeCheckBox(chkShowAlbumPath);
rGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
final View v;
switch (i) {
case R.id.radio_card_compact:
v = LayoutInflater.from(getActivity()).inflate(CardViewStyle.COMPACT.getLayout(), null);
v.findViewById(R.id.ll_album_info).setBackgroundColor(ColorPalette.getTransparentColor(getActivity().getBackgroundColor(), 150));
break;
case R.id.radio_card_flat:
v = LayoutInflater.from(getActivity()).inflate(CardViewStyle.FLAT.getLayout(), null);
v.findViewById(R.id.ll_album_info).setBackgroundColor(ColorPalette.getTransparentColor(getActivity().getBackgroundColor(), 150));
break;
case R.id.radio_card_material: default:
v = LayoutInflater.from(getActivity()).inflate(CardViewStyle.MATERIAL.getLayout(), null);
v.findViewById(R.id.ll_album_info).setBackgroundColor(getActivity().getCardBackgroundColor());
break;
}
ImageView img = v.findViewById(R.id.album_preview);
img.setBackgroundColor(getActivity().getPrimaryColor());
Glide.with(getActivity())
.load(R.drawable.donald_header)
.into(img);
String hexPrimaryColor = ColorPalette.getHexColor(getActivity().getPrimaryColor());
String hexAccentColor = ColorPalette.getHexColor(getActivity().getAccentColor());
if (hexAccentColor.equals(hexPrimaryColor))
hexAccentColor = ColorPalette.getHexColor(ColorPalette.getDarkerColor(getActivity().getAccentColor()));
String textColor = getActivity().getBaseTheme().equals(Theme.LIGHT) ? "#2B2B2B" : "#FAFAFA";
String albumPhotoCountHtml = "<b><font color='" + hexAccentColor + "'>420</font></b>";
((TextView) v.findViewById(R.id.album_media_count)).setText(StringUtils.html(albumPhotoCountHtml));
((TextView) v.findViewById(R.id.album_media_label)).setTextColor(getActivity().getTextColor());
((TextView) v.findViewById(R.id.album_path)).setTextColor(getActivity().getSubTextColor());
v.findViewById(R.id.ll_media_count).setVisibility( chkShowMediaCount.isChecked() ? View.VISIBLE : View.GONE);
chkShowMediaCount.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
v.findViewById(R.id.ll_media_count).setVisibility(b ? View.VISIBLE : View.GONE);
}
});
v.findViewById(R.id.album_path).setVisibility( chkShowAlbumPath.isChecked() ? View.VISIBLE : View.GONE);
chkShowAlbumPath.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
v.findViewById(R.id.album_path).setVisibility(b ? View.VISIBLE : View.GONE);
}
});
((TextView) v.findViewById(R.id.album_name)).setText(StringUtils.html("<i><font color='" + textColor + "'>PraiseDuarte</font></i>"));
((TextView) v.findViewById(R.id.album_path)).setText("~/home/PraiseDuarte");
((CardView) v).setUseCompatPadding(true);
((CardView) v).setRadius(2);
((LinearLayout) dialogLayout.findViewById(R.id.ll_preview_album_card)).removeAllViews();
((LinearLayout) dialogLayout.findViewById(R.id.ll_preview_album_card)).addView(v);
}
});
switch (Prefs.getCardStyle()) {
case CardViewStyle.COMPACT: rCompact.setChecked(true); break;
case CardViewStyle.FLAT: rFlat.setChecked(true); break;
case CardViewStyle.MATERIAL: default: rMaterial.setChecked(true); break;
}
builder.setNegativeButton(getActivity().getString(R.string.cancel).toUpperCase(), null);
builder.setPositiveButton(getActivity().getString(R.string.ok_action).toUpperCase(), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
CardViewStyle cardViewStyle;
switch (rGroup.getCheckedRadioButtonId()) {
case R.id.radio_card_material:
default:
cardViewStyle = CardViewStyle.MATERIAL;
break;
case R.id.radio_card_flat:
cardViewStyle = CardViewStyle.FLAT;
break;
case R.id.radio_card_compact:
cardViewStyle = CardViewStyle.COMPACT;
break;
}
Prefs.setCardStyle(cardViewStyle);
Prefs.setShowMediaCount(chkShowMediaCount.isChecked());
Prefs.setShowAlbumPath(chkShowAlbumPath.isChecked());
Toast.makeText(getActivity(), getActivity().getString(R.string.restart_app), Toast.LENGTH_SHORT).show();
}
});
builder.setView(dialogLayout);
builder.show();
}
}
As per Java docs
The Identifier in a EnumConstant may be used in a name to refer to the enum constant.
so we need to use the name only in case of an enum.
Change to this
switch (Prefs.getCardStyle()) {
case COMPACT: rCompact.setChecked(true); break;
case FLAT: rFlat.setChecked(true); break;
case MATERIAL: default: rMaterial.setChecked(true); break;
}

TabLayout fragments are instantiated as the same when debugger is not connected

I have a TabLayout that uses a custom adaptor (TabPagerAdapter.java), it's initialised with this function (I previously had the problem that things didn't update when replaced so it removes everything before initializing):
public boolean setPagerViewContents(int mode, ArrayList<String> titles) {
try {
mTabLayout.removeAllTabs();
mViewPager.setAdapter(null);
mViewPager.removeAllViews();
for (int i = 0; i < titles.size(); i++) {
mTabLayout.addTab(mTabLayout.newTab().setText(titles.get(i)));
}
mAdapter = new TabPagerAdapter(getSupportFragmentManager(), titles.size(), mode);
mViewPager.setAdapter(mAdapter);
mViewPager.invalidate();
return true;
} catch (Exception e) {
mErrorReporter.reportError(e);
return false;
}
}
Custom adapter (TabPageAdapter.java):
public class TabPagerAdapter extends FragmentStatePagerAdapter {
int mTabCount;
int mLayoutType;
public TabPagerAdapter(FragmentManager fm, int numberOfTabs, int layoutType) {
super(fm);
this.mTabCount = numberOfTabs;
this.mLayoutType = layoutType;
}
#Override
public Fragment getItem(int position) {
switch (mLayoutType) {
case 0:
switch (position) {
case 0:
return new Fragment15();
case 1:
return new Fragment1();
default:
return null;
}
case 1:
switch (position) {
case 0:
return new Fragment3();
case 1:
return new Fragment2();
default:
return null;
}
default:
return null;
}
}
#Override
public int getCount() {
return mTabCount;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
When the app starts the function setPagerViewContents (with the right mode and titles) is called, after that mViewPager.setCurrentItem(number) is called to display the right tab. But now the fragment displayed in mViewPager is correct but when clicking on a tab title the fragment is the same displayed at start (the one with the index number, not the one that should have been displayed), when tapping the first (number) tab again and then again to some other tab (not number) the shown tab is correct.
The most annoying thing here is that it's NOT consistent, it sometimes happens, sometimes doesn't and it doesn't happen when the debugger is attached so I can't debug it properly. If some other code is needed please do tell, I'll update this post as quick as possible because I'd really love to see this solved, for my own sanity and for the happiness of my few users.
Change your following method:
public boolean setPagerViewContents(int mode, ArrayList<String> titles) {
try {
mAdapter = new TabPagerAdapter(getSupportFragmentManager(), titles.size(), mode);
mViewPager.setAdapter(mAdapter);
mTabLayout.setupWithViewPager(mViewPager);
return true;
} catch (Exception e) {
mErrorReporter.reportError(e);
return false;
}
}
and set text on tabs in TabPagerAdapter by overriding following method:
#Override
public CharSequence getPageTitle(int position) {
return context.getString(tabTitles[position]);
}

onchildclick case statement android

the project run ok,the case 3 child clicks ok ,but in case 2 clicks it display activity from case 3 or activity that I deleted it before then on return it display the activity that I wanted
(when I click microbiology it display pedodontics then on return click it display Microbiology)
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.Toast;
import com.freedental.blogspot.R;
public class MainActivity extends Activity {
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the listview
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
// Listview Group click listener
expListView.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
// Toast.makeText(getApplicationContext(),
// "Group Clicked " + listDataHeader.get(groupPosition),
// Toast.LENGTH_SHORT).show();
return false;
}
});
// Listview Group expanded listener
expListView.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Expanded",
Toast.LENGTH_SHORT).show();
}
});
// Listview Group collasped listener
expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Collapsed",
Toast.LENGTH_SHORT).show();
}
});
// Listview on child click listener
expListView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
switch(groupPosition) {
case 1:
switch (childPosition) {
case 0:
Intent c1= new Intent(MainActivity.this,Webv1Activity.class);
startActivity(c1);
break;
}
case 2:
switch (childPosition) {
case 0:
Intent d1= new Intent(MainActivity.this,Webv1Activity.class);
startActivity(d1);
break;
case 1:
Intent d2= new Intent(MainActivity.this,Webv2Activity.class);
startActivity(d2);
break;
case 2:
Intent d3= new Intent(MainActivity.this,Webv3Activity.class);
startActivity(d3);
break;
case 3:
Intent d4= new Intent(MainActivity.this,Webv4Activity.class);
startActivity(d4);
break;
case 4:
Intent d5= new Intent(MainActivity.this,Webv5Activity.class);
startActivity(d5);
break;
case 5:
Intent d6= new Intent(MainActivity.this,Webv6Activity.class);
startActivity(d6);
break;
case 6:
Intent d7= new Intent(MainActivity.this,Webv7Activity.class);
startActivity(d7);
break;
case 7:
Intent d8= new Intent(MainActivity.this,Webv8Activity.class);
startActivity(d8);
break;
}
case 3:
switch (childPosition) {
case 0:
Intent a1= new Intent(MainActivity.this,Webv9Activity.class);
startActivity(a1);
break;
case 1:
Intent a2= new Intent(MainActivity.this,Webv10Activity.class);
startActivity(a2);
break;
case 2:
Intent a3= new Intent(MainActivity.this,Webv11Activity.class);
startActivity(a3);
break;
case 3:
Intent a4= new Intent(MainActivity.this,Webv12Activity.class);
startActivity(a4);
break;
case 4:
Intent a5= new Intent(MainActivity.this,Webv13Activity.class);
startActivity(a5);
break;
case 5:
Intent a6= new Intent(MainActivity.this,Webv14Activity.class);
startActivity(a6);
break;
case 6:
Intent a7= new Intent(MainActivity.this,Webv15Activity.class);
startActivity(a7);
break;
case 7:
Intent a8= new Intent(MainActivity.this,Webv16Activity.class);
startActivity(a8);
break;
}
}
return false;
}
});
}
/*
* Preparing the list data
*/
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data
listDataHeader.add("1st Grade lectures");
listDataHeader.add("2nd Grade lectures");
listDataHeader.add("3rd Grade lectures");
listDataHeader.add("4th Grade lectures");
listDataHeader.add("5th Grade lectures");
// Adding child data
List<String> first = new ArrayList<String>();
first.add("Under Construction");
List<String> second = new ArrayList<String>();
second.add("Prosthodontics");
second.add("Other under con");
List<String> third = new ArrayList<String>();
third.add("Microbiology");
third.add("Pathology");
third.add("Pharmacology");
third.add("Surgery");
third.add("Operative");
third.add("Prosthodontics");
third.add("Radiology");
third.add("Cummunity");
List<String> fourth = new ArrayList<String>();
fourth.add("periodontology");
fourth.add("pedodontics");
fourth.add("Orthodontics");
fourth.add("Prosthodontics");
fourth.add("Oral Pathology");
fourth.add("Oral Surgery");
fourth.add("General Surgery");
fourth.add("General Medicine");
List<String> fifth = new ArrayList<String>();
fifth.add("Under Construction");
listDataChild.put(listDataHeader.get(0), first); // Header, Child data
listDataChild.put(listDataHeader.get(1), second);
listDataChild.put(listDataHeader.get(2), third);
listDataChild.put(listDataHeader.get(3), fourth);
listDataChild.put(listDataHeader.get(4), fifth);
}
}
You are missing a break statement after case 1 and case 2 :
expListView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
switch(groupPosition) {
case 1:
switch (childPosition) {
case 0:
Intent c1= new Intent(MainActivity.this,Webv1Activity.class);
startActivity(c1);
break;
}
=======>>>>> break;
case 2:
switch (childPosition) {
case 0:
Intent d1= new Intent(MainActivity.this,Webv1Activity.class);
startActivity(d1);
break;
case 1:
Intent d2= new Intent(MainActivity.this,Webv2Activity.class);
startActivity(d2);
break;
case 2:
Intent d3= new Intent(MainActivity.this,Webv3Activity.class);
startActivity(d3);
break;
case 3:
Intent d4= new Intent(MainActivity.this,Webv4Activity.class);
startActivity(d4);
break;
case 4:
Intent d5= new Intent(MainActivity.this,Webv5Activity.class);
startActivity(d5);
break;
case 5:
Intent d6= new Intent(MainActivity.this,Webv6Activity.class);
startActivity(d6);
break;
case 6:
Intent d7= new Intent(MainActivity.this,Webv7Activity.class);
startActivity(d7);
break;
case 7:
Intent d8= new Intent(MainActivity.this,Webv8Activity.class);
startActivity(d8);
break;
}
==========>>>>> break;
case 3:
switch (childPosition) {
case 0:
Intent a1= new Intent(MainActivity.this,Webv9Activity.class);
startActivity(a1);
break;
case 1:
Intent a2= new Intent(MainActivity.this,Webv10Activity.class);
startActivity(a2);
break;
case 2:
Intent a3= new Intent(MainActivity.this,Webv11Activity.class);
startActivity(a3);
break;
case 3:
Intent a4= new Intent(MainActivity.this,Webv12Activity.class);
startActivity(a4);
break;
case 4:
Intent a5= new Intent(MainActivity.this,Webv13Activity.class);
startActivity(a5);
break;
case 5:
Intent a6= new Intent(MainActivity.this,Webv14Activity.class);
startActivity(a6);
break;
case 6:
Intent a7= new Intent(MainActivity.this,Webv15Activity.class);
startActivity(a7);
break;
case 7:
Intent a8= new Intent(MainActivity.this,Webv16Activity.class);
startActivity(a8);
break;
}
}
return false;
}
});

Switch statement just returning the last case

Switch statment fix:
The switch statement is only returning the last case i.e case 4, "#0R0dfdf0FF". how can i fix this so the text view shows the the one clicked in the dialogue box?
I'm a total newbie so yes help would really be appreciated.
public class NoteEdit extends Activity {
public EditText mTitleText;
public EditText mBodyText;
public EditText mColor;
private NotesDbAdapter mDbHelper;
private static final int DIALOG_ALERT = 10;
Long mRowId;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
setContentView(R.layout.note_edit);
setTitle(R.string.done);
mTitleText = (EditText) findViewById(R.id.editTitle);
mBodyText = (EditText) findViewById(R.id.editNote);
mColor = (EditText) findViewById(R.id.editColor);
mRowId = (savedInstanceState == null) ? null :
(Long) savedInstanceState.getSerializable(NotesDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID)
: null;
}
populateFields();
setupActionBar();
}
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
setResult(RESULT_OK);
finish();
}
return super.onOptionsItemSelected(item);
}
private void populateFields() {
if (mRowId != null) {
Cursor note = mDbHelper.fetchNote(mRowId);
startManagingCursor(note);
mTitleText.setText(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
mBodyText.setText(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
mColor.setText(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_COLOR)));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(NotesDbAdapter.KEY_ROWID, mRowId);
}
#Override
protected void onPause() {
super.onPause();
saveState();
}
#Override
protected void onResume() {
super.onResume();
populateFields();
}
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
String color = mColor.getText().toString();
if (mRowId == null) {
long id = mDbHelper.createNote(title, body, color);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateNote(mRowId, title, body, color);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()) {
case R.id.add:
showDialog(DIALOG_ALERT);
return true;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_ALERT:
// Create out AlterDialog
android.app.AlertDialog.Builder builder = new AlertDialog.Builder(this);
final String[] colors = {"Blue", "Green", "Yellow", "Red", "Purple"};
builder.setTitle(R.string.body);
builder.setItems(colors, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which){
case 0:
mColor.setText("#000000");
case 1:
mColor.setText("#0000FF");
case 2:
mColor.setText("#0R00FF");
case 3:
mColor.setText("#0R00dsdFF");
case 4:
mColor.setText("#0R0dfdf0FF");
default:
break;
}
} });
AlertDialog dialog = builder.create();
dialog.show();
}
return super.onCreateDialog(id);
}
}
You are missing break; at the end of the switch branches.
Fall Through.
You have to add the break.
case 0:
mColor.setText("#000000");
break;
You can find that in docs
The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.
You need a break when you don't have a return otherwise it causes fall through
You need the break; after all cases except for the last one or else it'll fall through case by case
switch (which){
case 0:
mColor.setText("#000000");
break;
case 1:
mColor.setText("#0000FF");
break;
case 2:
mColor.setText("#0R00FF");
break;
case 3:
mColor.setText("#0R00dsdFF");
break;
case 4:
mColor.setText("#0R0dfdf0FF");
default:
break;
}

Android: how to create Switch case from this?

public void onItemClick(AdapterView<?> a, View v, int position, long id) {
AlertDialog.Builder adb = new AlertDialog.Builder(CategoriesTab.this);
adb.setTitle("Selected Category");
adb.setMessage("Selected Item is = "+lv1.getItemAtPosition(position));
adb.setPositiveButton("Ok", null);
adb.show();
}
This at the moment displays an alertbox when an item from listview is clicked. I want to convert the alertbox to load a specific xml for each choices clicked. How can i do this?
thanks for your help.
switch(position) {
case 0:
setContentView(R.layout.xml0);
break;
case 1:
setContentView(R.layout.xml1);
break;
default:
setContentView(R.layout.default);
break;
}
i hope this will do the job!
#Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.:
break;
case R.id.:
break;
default:
break;
}
}
switch(position) {
case 0:
...
break;
case 1:
...
break;
default:
...
}
Did you mean that?
You can do this:
#Override
protected Dialog onCreateDialog(int id) {
String messageDialog;
String valueOK;
String valueCancel;
String titleDialog;
switch (id) {
case id:
titleDialog = itemTitle;
messageDialog = itemDescription
valueOK = "OK";
return new AlertDialog.Builder(HomeView.this).setTitle(titleDialog).setPositiveButton(valueOK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Log.d(this.getClass().getName(), "AlertItem");
}
}).setMessage(messageDialog).create();
and then call to
showDialog(numbreOfItem);

Categories