onchildclick case statement android - java

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;
}
});

Related

Enusuring spinner value selected, or button not allowed to be selected

I am new to android studio and have created an app with a page that enables 2 spinners to be selected, a user enters a time and then an 'end time' is calculated. I am trying to add some validation to this page as when I click the 'VerifyButton' the app crashes as no fields have been selected. My intention is that when the user selects the 'VerifyButton' that an error message displays to ensure the spinner values have been filled in, meaning the app doesn't crash. I have tried a few methods within the onNothingSelected but it doesn't seem to work.. I wasn't sure if it needs to be in there or the VerifyButton? Thanks in advance!
Spinner Java
final ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(CreateLine.this,
R.layout.spinner_layout, getResources().getStringArray(R.array.LineTypes));
myAdapter.setDropDownViewResource(R.layout.spinner_layout);
spinner.setAdapter(myAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position2, long l) {
switch (position2) {
case 0:
quantity.setText("");
break;
case 1:
quantity.setVisibility(View.INVISIBLE);
timeadded = 10;
duration.setText(timeadded + " Hours");
spinner2.setVisibility(View.INVISIBLE);
break;
case 2:
quantity.setVisibility(View.INVISIBLE);
timeadded = 10;
duration.setText(timeadded + " Hours");
spinner2.setVisibility(View.INVISIBLE);
break;
case 3:
quantity.setVisibility(View.INVISIBLE);
timeadded = 10;
duration.setText(timeadded + " Hours");
spinner2.setVisibility(View.INVISIBLE);
break;
case 4:
quantity.setVisibility(View.VISIBLE);
duration.setText(timeadded + " Hours");
spinner2.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "Select Package Type", Toast.LENGTH_SHORT).show();
break;
case 5:
quantity.setVisibility(View.VISIBLE);
duration.setText(timeadded + " Hours");
spinner2.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "Select Package Type", Toast.LENGTH_SHORT).show();
break;
case 6:
quantity.setVisibility(View.VISIBLE);
duration.setText(timeadded + " Hours");
spinner2.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "Select Package Type", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
ArrayAdapter<String> myAdapter2 = new ArrayAdapter<String>(CreateLine.this,
R.layout.spinner_layout, getResources().getStringArray(R.array.PackageTypes));
myAdapter2.setDropDownViewResource(R.layout.spinner_layout);
spinner2.setAdapter(myAdapter2);
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
switch (position) {
case 0:
quantity.setText("");
break;
case 1:
quantity.setText(PackageType20);
timeadded = 28;
duration.setText(timeadded + " Hours");
break;
case 2:
quantity.setText(PackageType30);
timeadded = 27;
duration.setText(timeadded + " Hours");
break;
default:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
VerifyButton Java
VerifyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
spinnerSelection = String.valueOf(spinner.getSelectedItem());
spinnerSelection2 = String.valueOf(spinner2.getSelectedItem());
String q = quantity.getText().toString();
String d = duration.getText().toString();
DateTime datetime = new DateTime(yearNow, monthNow, dayNow, hourNow, minuteNow);
DateTimeFormatter fmt = DateTimeFormat.forPattern("EE dd MM yyyy" + "\n" + " h:mm a ");
String formattedtime = fmt.print(datetime);
CalculateButton.setText(formattedtime);
// Plus some hours, minutes, and seconds to the original DateTime.
DateTimeFormatter fmt2 = DateTimeFormat.forPattern("EE dd MM yyyy" + "\n" + " h:mm a ");
DateTime dateTime1 = datetime.plusHours(timeadded);
String endtimecalc = fmt2.print(dateTime1);
TextView endtime = findViewById(endtimetextView);
endtime.setVisibility(View.VISIBLE);
endtime.setText(endtimecalc);
if (spinnerSelection !=null) {
Toast.makeText(getApplicationContext(),"enter value",
Toast.LENGTH_LONG).show();
}
//INSERT DATA TO DATABASE
boolean isInserted = myDb.insertData(
spinnerSelection,
spinnerSelection2,
q,
d,
formattedtime,
endtimecalc);
if (isInserted == true)
Toast.makeText(CreateLine.this, "Data Inserted Successfully", Toast.LENGTH_LONG).show();
else
Toast.makeText(CreateLine.this, "This line is already Active!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(), Dashboard.class);
startActivity(intent);
}
});
Replace all of your :
getApplicationContext()
with:
getContext()
and in following line instead of getApplicationContext():
Intent intent = new Intent(getApplicationContext(), Dashboard.class);
Use your class name as follows:
Intent intent = new Intent(YourClassName.this, Dashboard.class);
Class in which you are defining your verify button.
And in both of onNothingSelected methods set default value for spinner as:
ArrayList<String> list = getResources().getStringArray(R.array.LineTypes);
yourSpinner.setSelection(list[0]);
Also apply check instead of this:
if (spinnerSelection !=null) {
Toast.makeText(getApplicationContext(),"enter value",
Toast.LENGTH_LONG).show();
}
As:
if (spinnerSelection.getSelectedItem().toString().isEmpty() || spinnerSelection.getSelectedItem().toString() == "" )
{
Toast.makeText(getApplicationContext(),"enter value",
Toast.LENGTH_LONG).show();
}
After spinner.setAdapter(myAdapter) add;
spinner.setAdapter(myAdapter)
spinner.setSelection(-1);
then on verify button click:
if (spinner.getSelectedItemPosition() == -1 || spinner2.getSelectedItemPosition() == -1 ){
// showErrorMessage
}
else{
//do your work
}
Do the same for spinner2

How to use switch case with string resources

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;
}

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;
}

Why not change color when pressed?

when you click the color should change to another
but it doesnt work!
My code:
#
public class CreateActivity extends Activity {
TableLayout table;
Integer i;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
table = (TableLayout)findViewById(R.id.myTable);
Button left = (Button) findViewById(R.id.buttonLeft);
Button right = (Button) findViewById(R.id.buttonRight);
TextView color = (TextView) findViewById(R.id.text);
i=0;
right.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
i++; //+1
}
});
//COLOR
switch(i){
case 1: table.setBackgroundColor(Color.RED); break;
case 2: table.setBackgroundColor(Color.rgb (255, 127, 0) ); break;
case 3: table.setBackgroundColor(Color.YELLOW); break;
case 4: table.setBackgroundColor(Color.GREEN) ; break;
case 5: table.setBackgroundColor(Color.rgb (0,191,255) ); break;
case 6: table.setBackgroundColor(Color.BLUE ); break;
case 7: table.setBackgroundColor(Color.rgb (160,32,240) ); break;
}
}
}
When the button is clicked, you're incrementing i - but you won't be running the switch/case statement again. If you look in the debugger you'll find that the variable value is changing, but you haven't instructed any part of the display to change.
You should put that common logic in a separate method which is called both from the onCreate method and the OnClickListener. For example:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
table = (TableLayout)findViewById(R.id.myTable);
Button left = (Button) findViewById(R.id.buttonLeft);
Button right = (Button) findViewById(R.id.buttonRight);
TextView color = (TextView) findViewById(R.id.text);
i=0;
right.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
i++;
// Cycle round
if (i == 8) {
i = 1;
}
applyBackgroundColor();
}
});
applyBackgroundColor();
}
private void applyBackgroundColor() {
switch(i) {
// TODO: Consider what you want to do when i is 0...
case 1: table.setBackgroundColor(Color.RED); break;
case 2: table.setBackgroundColor(Color.rgb(255, 127, 0)); break;
case 3: table.setBackgroundColor(Color.YELLOW); break;
case 4: table.setBackgroundColor(Color.GREEN); break;
case 5: table.setBackgroundColor(Color.rgb(0,191,255)); break;
case 6: table.setBackgroundColor(Color.BLUE); break;
case 7: table.setBackgroundColor(Color.rgb(160,32,240)); break;
}
}
There are various other things I'd change about this code, but that should at least get you over this hump.

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