Unreachable code android - android

I am programming this whole day and now i am stuck with unreachable after return; at
return;
Recipe093.path[1] = localCursor.getString(1);
If i remove return i get unreachable code after continue;
Why do I get unreachable code?
Hope someone can help me and Thanks.
Here is my code:
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
setContentView(R.layout.musiclist);
final Cursor localCursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, (String[])null, null, (String[])null, null);
String[] arrayOfString1 = localCursor.getColumnNames();
int i = arrayOfString1.length;
for (int j = 0; ; j++)
{
if (j >= i)
{
String[] arrayOfString2 = { "title", "artist", "duration" };
int[] arrayOfInt = { 2131099668, 2131099669, 2131099670 };
SimpleCursorAdapter localSimpleCursorAdapter = new SimpleCursorAdapter(getApplicationContext(), 2130903044, localCursor, arrayOfString2, arrayOfInt);
localSimpleCursorAdapter.setViewBinder(new AudioListViewBinder());
ListView localListView = (ListView)findViewById(2131099667);
localListView.setAdapter(localSimpleCursorAdapter);
Log.d("test", "start list()");
localListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> paramAnonymousAdapterView, View paramAnonymousView, int paramAnonymousInt, long paramAnonymousLong)
{
switch (Recipe093.this.getIntent().getIntExtra("case1", 0))
{
default:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
}
while (true)
{
Intent localIntent = new Intent(Recipe093.this.getApplicationContext(), MainActivity.class);
Recipe093.this.startActivity(localIntent);
return;
Recipe093.path[1] = localCursor.getString(1);
SharedPreferences.Editor localEditor10 = Recipe093.this.getSharedPreferences("FileName", 3).edit();
localEditor10.putString("userChoice", Recipe093.path[1]);
localEditor10.commit();
continue;
Recipe093.path[2] = localCursor.getString(1);
SharedPreferences.Editor localEditor9 = Recipe093.this.getSharedPreferences("FileName", 3).edit();
localEditor9.putString("userChoice1", Recipe093.path[2]);
localEditor9.commit();
}
}
});
return;
}
Log.d("Recipe093", arrayOfString1[j]);
}
}
private class AudioListViewBinder
implements SimpleCursorAdapter.ViewBinder
{
private AudioListViewBinder()
{
}
public boolean setViewValue(View paramView, Cursor paramCursor, int paramInt) {
// TODO Auto-generated method stub
int i = paramCursor.getColumnIndex("title");
int j = paramCursor.getColumnIndex("artist");
int k = paramCursor.getColumnIndex("duration");
if ((paramInt == i) || (paramInt == j))
((TextView)paramView).setText(paramCursor.getString(paramInt));
return false;
}
}
}

Basically, return; means "exit this method now". So anything after a return statement is not run.
You can use scope to have multiple returns:
if(x == 1) {
return;
// Nothing will be called here on down in this scope, i.e. before `}`
}
x = 1;
return;
// Nothing will be called here on down

If you can return; the code stops and returns to the first method. It will not run any code after this line. The same story with break;

As Sam said (you should accept his answer), return means exit now.
However, return for a method which returns void is optional, since the closing brace for the method will also return:
These are equivalent:
void someMethod(){
doSomeStuff();
return;
}
void someMethod(){
doSomeStuff();
}
It is considered bad practice to use return in a void method unless you want to return early but, any explicit return must be conditional, i.e. part of a switch or if statement. If they are not conditional, then the compiler knows that the method will always exit at that point and any code after it cannot possibly execute, hence the compiler error you are seeing.
To most Java coders, the first example just looks wrong.
PS. while(true) is horrible but, if you want to get out of that loop early, you should use break which will transfer execution to the statement after the end of the while loop, not return.

Related

How can I determine what causes app to stop running

My app compiles without issue, other than a warning about cursor deprecation, and is deployed and runs correctly but stops after a few minutes and asks 'open app again?'. It reopens correctly.
The crash report is below but I have no idea how to interpret it.
The app is a simple database that shows steel section properties.
Any suggestions on where to start looking gratefully received.
The code of all 3 activities is here
http://silverfernsolutions.com/Code_for_stackoverflow_55308480.txt
Min version code is below. I can only test this on the Studio AVD by getting to the DisplaySectionProperties screen and then turning the emulator off and on. The display reverts to ShowSelectedSource screen when turned back on and sometimes triggers the error message.
UPDATE-RESOLVED The problem goes away when the lines
c.close();
mDbHelper.close();
in DisplaySectionProperties onCreate() are removed. This implies it is a problem with the way the DB is being used and that is a different question.
a java.lang.RuntimeException:
at android.app.ActivityThread.performResumeActivity (ActivityThread.java:3790)
at android.app.ActivityThread.handleResumeActivity (ActivityThread.java:3830)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1746)
at android.os.Handler.dispatchMessage (Handler.java:105)
at android.os.Looper.loop (Looper.java:164)
at android.app.ActivityThread.main (ActivityThread.java:6944)
at java.lang.reflect.Method.invoke (Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run (Zygote.java:327)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1374)
Caused by: java.lang.IllegalStateException:
at android.app.Activity.performRestart (Activity.java:7322)
at android.app.Activity.performResume (Activity.java:7353)
at android.app.ActivityThread.performResumeActivity (ActivityThread.java:3765)
CODE
public class MainActivity extends AppCompatActivity{
String DB_NAME = "SteelSectionProperties";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.icon);
setSupportActionBar(toolbar);
// Display icon in the toolbar
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayUseLogoEnabled(true);
deleteDatabase(DB_NAME); //7Aug2011. Reload each time to pick up any upgrades
DataBaseHelperReign myDbHelper;// = new DataBaseHelperReign(this);
myDbHelper = new DataBaseHelperReign(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
//Toast.makeText(MainActivity.this, "Unable to create DB", Toast.LENGTH_LONG).show();
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
} catch (SQLException sqle) {
//Toast.makeText(MainActivity.this, "Unable to open DB", Toast.LENGTH_LONG).show();
throw sqle;
}
myDbHelper.close();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String units = prefs.getString("displayunitskey", "1");
if (units == "1") {
//first use. Set mm as initial default setting
SharedPreferences.Editor editor = prefs.edit();
editor.putString("displayunitskey", "mm");
editor.commit();
}
}//end oncreate
public void onClick(View v) {
// Perform action on click
int Idx = 0;
int id = v.getId();
switch (id) {
case R.id.btn0: Idx = 0; break;
case R.id.btn1: Idx = 1; break;
case R.id.btn2: Idx = 2; break;
case R.id.btn3: Idx = 3; break;
case R.id.btn4: Idx = 4; break;
case R.id.btn5: Idx = 5; break;
case R.id.btn6: Idx = 6; break;
case R.id.btn7: Idx = 7; break;
} //end switch
runIntents(Idx);
}//end onClick
/**/
private void runIntents(int idx) {
if (idx == 0) {
//Intent i = new Intent(this, UserSectionInput.class);
//startActivity(i);
} else {
Intent i = new Intent(this, ShowSelectedSource.class);
i.putExtra("ButtonID", idx);
startActivity(i);
} //endif
}//end runintents
}
public class ShowSelectedSource extends ListActivity{
long mSelSectionID;
String mSource, mSourceFile;
String mTable;
private SectionsDbAdapter mDbHelper;
private SectionsUserDbAdapter mDbUserHelper;
private int BtnId;
TextView tv_section, lblListSection;
ImageView imgListSection;
ImageView imgIcon;
Button btn6; //Tee shape
String mSorting ="DESC"; //ASC or DESC (default)
String mShape="A"; //default
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_selected_source);
Bundle bundle = getIntent().getExtras();
BtnId = bundle.getInt("ButtonID");
lblListSection= findViewById(R.id.lblListSection);
imgListSection= findViewById(R.id.imgListSection);
btn6 = findViewById(R.id.btn6);
mDbHelper = new SectionsDbAdapter(this);
mDbUserHelper = new SectionsUserDbAdapter(this);
//Button clicked on opening screen
switch (BtnId){
case 0://custom, already gone in Main to section input screen
case 1: mSource="CU"; mSourceFile="Saved user sections"; break; //user saved sections
case 2: mSource="US"; mSourceFile="American "; break;
case 3: mSource="AU"; mSourceFile="Australian "; break;
case 4: mSource="UK"; mSourceFile="British "; break;
case 5: mSource="EU"; mSourceFile="European "; break;
case 6: mSource="JA"; mSourceFile="Japan "; break;
case 7: mSource="TU"; mSourceFile="Tubes "; break;
}//end switch
if ( BtnId == 1){
mTable="SectionUser";
mDbUserHelper.open();
}else{
mTable="SectionProps";
mDbHelper.open();
btn6.setVisibility(View.GONE); //turn off Tee button
}
initialDisplay();
} // end onCreate ///////////////////////////////////////////////
private void initialDisplay(){
//open display
lblListSection.setText(mSourceFile);
Cursor c=null;
try{
if ( BtnId == 1){
c = mDbUserHelper.fetchRecordsbySource(mTable, mSource);
}else{
c = mDbHelper.fetchRecordsbySourceReverse(mTable, mSource,mSorting);
}
startManagingCursor(c);
} catch (SQLException e){
e.printStackTrace();
}
String[] from = new String[] {SectionsDbAdapter.KEY_DESC }; //The column(s) that the data are from
int[] to = new int[] { R.id.tv_full_width }; // int array containing references to the views that we'll bind the data into (the R.id.text1 TextView).
SimpleCursorAdapter records =
new SimpleCursorAdapter(this, R.layout.section_row_full_width, c, from, to); //the .xml file containing the R.id.xxxx
setListAdapter(records);
//c.close(); don't close, it stuffs up the buttons for some reason
}
private void loadListView(){
setImage();
Cursor c=null;
try{
if (mShape.equals("A")){
if ( BtnId == 1){
c = mDbUserHelper.fetchRecordsbySourceReverse(mTable, mSource,mSorting);
}else{
c = mDbHelper.fetchRecordsbySourceReverse(mTable, mSource, mSorting);
}
}else{
if ( BtnId == 1){
c = mDbUserHelper.fetchRecordsbySourceShapeReverse(mTable, mSource, mShape, mSorting);
}else{
c = mDbHelper.fetchRecordsbySourceShapeReverse(mTable, mSource, mShape, mSorting);
}
}
startManagingCursor(c);
String[] from = new String[] {SectionsDbAdapter.KEY_DESC }; //The column(s) that the data are from
int[] to = new int[] { R.id.tv_full_width }; // int array containing references to the views that we'll bind the data into (the R.id.text1 TextView).
SimpleCursorAdapter records =
new SimpleCursorAdapter(this, R.layout.section_row_full_width, c, from, to); //the .xml file containing the R.id.xxxx
setListAdapter(records);
//c.close(); don't close, it stuffs up the buttons for some reason
} catch (SQLException e){
e.printStackTrace();
}
}//end loadview
//get button clicks for filtering
public void onButtonClick(View v) {
switch ( v.getId()) {
case R.id.btn0: mShape="A" ;break; //all
case R.id.btn1: mShape="I";break;
case R.id.btn2: mShape="["; break;
case R.id.btn3: mShape="[]"; break;
case R.id.btn4: mShape="O";break;
case R.id.btn5: mShape="L";break;
case R.id.btn6: mShape="T";break;
case R.id.btnsort:
if (mSorting.equals("DESC")){
mSorting="ASC";
} else {
mSorting="DESC";
}
break;
} //end switch
loadListView();
}//end onClick buttons
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id); // Get the item that was clicked
v.setBackgroundColor(Color.rgb(127, 255, 0));
// next screen to display properties
Intent i = new Intent(this, DisplaySectionProperties.class);
i.putExtra("ButtonID",BtnId);
i.putExtra("Table",mTable);
i.putExtra("TablerowID", id);
Log.e("in select, Tablerow", " id = " +id);
startActivity(i);
}// end onclick listview
} //end class
public class DisplaySectionProperties extends AppCompatActivity {
private String mTable;
private long mTablerowID;
private int mBtnId;
private String mShape;
private String mDescription;
private double mDepth, mtw,mb1, mt1, mb2, mt2;
private String mDisplayUnits; // the units the user wants displayed
private String mSectionUnits; //the units that mS is currently using
private TextView txtDescription;
private ImageView imgShape;
//The section object
private cSectionProperties mS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_section_properties);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.icon);
setSupportActionBar(toolbar);
mS= new cSectionProperties();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences (this);
mDisplayUnits=prefs.getString("displayunitskey","1");
txtDescription= findViewById(R.id.lblDisplaySection);
imgShape= findViewById(R.id.imgDisplaySection);
Bundle bundle = getIntent().getExtras();
mBtnId = bundle != null ? bundle.getInt("ButtonID") : 0;
mTable = bundle != null ? bundle.getString("Table") : null;
mTablerowID= bundle.getLong("TablerowID");
Toast.makeText(this, "Disp Sect TablerowID := " + mTablerowID, Toast.LENGTH_LONG) .show();
if (mTablerowID == 0){
//user input section
mDescription=bundle.getString("Description");
mDepth=bundle.getDouble("Depth");
mtw=bundle.getDouble("tw");
mb1=bundle.getDouble("B1");
mt1=bundle.getDouble("T1");
mb2=bundle.getDouble("B2");
mt2=bundle.getDouble("T2");
mShape=bundle.getString("Shape");
mSectionUnits=bundle.getString("Units");
//createUserSection();
}else{
Cursor c;
try{
if(mTable.equals("SectionUser") ){
SectionsUserDbAdapter mDbHelper = new SectionsUserDbAdapter(this);
mDbHelper.open();
c = mDbHelper.fetchRecordbyID(mTable, mTablerowID+""); //convert int to string (v= v + "")= int V is now string
startManagingCursor(c);
mDescription= c.getString(c.getColumnIndex("Description"));
mDepth= c.getDouble(c.getColumnIndex("Depth"));
mtw = c.getDouble(c.getColumnIndex("tweb_wall"));
mb1= c.getDouble(c.getColumnIndex("Bf1"));
mt1= c.getDouble(c.getColumnIndex("Tf1"));
mb2= c.getDouble(c.getColumnIndex("Bf2"));
mt2= c.getDouble(c.getColumnIndex("Tf2"));
mShape= c.getString(c.getColumnIndex("Shape"));
mSectionUnits= c.getString(c.getColumnIndex("Units"));
c.close();
mDbHelper.close();
//createUserSection();
}else{
// section from the standard DB, mSectionUnits will be mm
SectionsDbAdapter mDbHelper = new SectionsDbAdapter(this);
mDbHelper.open();
c = mDbHelper.fetchRecordbyID(mTable, mTablerowID+""); //convert int to string (v= v + "")= int V is now string
startManagingCursor(c);
mDbHelper.close();
// createSection(c);
c.close();
}
} catch (SQLException e){
e.printStackTrace();
}
}//endif
// displayProperties();
} //end oncreate

Moving some functions from mainactivity into another class

I have a addAllToGroup click function and I use the DialogWithRadioButtonM in many different places, is it possible to place DialogWithRadioButtonM() and redioGroup1() functions in a separate file(class)? Here is my code:
i tried to put it in a class but i get error for onclicklistener in it and also i dont know how to use context in a nonActivity java file. sorry, I am new in android and java thanks for help.
public void addAllToGroup(View view) {
csM = new String[6];
//dialogTitle="Add This to Group";
csM[0] = "Add to Group 1";
csM[1] = "Add to Group 2";
csM[2] = "Add to Group 3";
csM[3] = "Add to Group 4";
csM[4] = "Add to Group 5";
csM[5] = "Remove Grouping";
DialogWithRadioButtonM("Add Selected to Group");
}
public void DialogWithRadioButtonM(String str){
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(str);
builder.setSingleChoiceItems(csM, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Log.i("TAG2", "onCreate: "+item);
switch(item)
{
case 0: backFromDialogM=0; break;
case 1: backFromDialogM=1; break;
case 2: backFromDialogM=2; break;
case 3: backFromDialogM=3; break;
case 4: backFromDialogM=4; break;
case 5: backFromDialogM=5; break;
case 6: backFromDialogM=6; break;
case 7: backFromDialogM=7; break;
}
redioGroup1(backFromDialogM);
alertDialogM.dismiss();
}
});
alertDialogM = builder.create();
alertDialogM.show();
}
public void redioGroup1(int group) {
int iCount = myRecycler.getAdapter().getItemCount();
MyDateBase mydbM = new MyDateBase(MainActivity.this);
final SQLiteDatabase databaseM = mydbM.getWritableDatabase();
String strCL = "cl" + "0";
String rawQueryM="";
for (int i = 0; i < iCount; i++) {
if (mAdapter.itemList.get(i).isChecked()) {
mAdapter.itemList.get(i).getuSentId();
rawQueryM ="UPDATE wp_words SET " + strCL + " =" + group + " WHERE wid= " + mAdapter.itemList.get(i).getuSentId();
databaseM.execSQL(rawQueryM);
Log.i("tog", "" + mAdapter.itemList.get(i).getuSentId());
}
}
Log.i("togf", "" + rawQueryM);
}
thanks
Your "DialogWithRadioButtonM" Class depends of the outer class in which it is.
You have to make "DialogWithRadioButtonM" not dependant of other variables/objects outside it, or you cannot move it in a stand alone Class file.
For example: "backFromDialogM" and "alertDialogM" are not declared INSIDE DialogWithRadioButtonM but somewhere else in the same file.

A simple calculator

I'm new to Android. I'm trying to develop my first calculator. My calculator output is good, but I'm trying to make some changes to it. Please suggest. My output is 2+2=4.0 How can I get 4 if I put 2+2 and 4.0 when I put 2.8+1.2.
Also, please help me out in trying to figure out how can i keep on adding till i press =.
My code that I'm looking at is below:
private View.OnClickListener buttonClickListerner = new
View.OnClickListener() {
float r;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.clear:
screen.setText("");
operator.setText("");
FirstNum= 0;
showtext.setText("");
break;
case R.id.buttonAdd:
mMath("+");
operator.setText("+");
showtext.setText(String.valueOf(FirstNum));
break;
case R.id.buttonMinus:
mMath("-");
operator.setText("-");
break;
case R.id.buttonMul:
mMath("*");
operator.setText("*");
break;
case R.id.buttonequal:
mResult();
break;
case R.id.buttonDiv:
mMath("/");
operator.setText("/");
break;
case R.id.buttonPercent:
mMath("%");
r = FirstNum / 100;
showtext.setText("[" + String.valueOf(FirstNum) + "%" + "]");
screen.setText(String.valueOf(r));
break;
default:
String num = ((Button) v).getText().toString();
getKeyboard(num);
break;
}
}
};
public void mMath(String str){
FirstNum = Float.parseFloat(screen.getText().toString());
operation = str;
screen.setText("");
}
public void getKeyboard(String str){
String CurrentScreen = screen.getText().toString();
if(CurrentScreen.equals("0"))
CurrentScreen = "";
CurrentScreen = CurrentScreen + str;
screen.setText(CurrentScreen);
String ExScreen = CurrentScreen;
screen.setText(ExScreen);
}
public void mResult(){
float SecondNum = Float.parseFloat(screen.getText().toString());
float ThirdNum = Float.parseFloat(screen.getText().toString());
float result = 0;
//float exresult = result;
if(operation.equals("+")){
result = FirstNum + SecondNum;
// exresult = result + ThirdNum;
}
if(operation.equals("-")){
result = FirstNum - SecondNum;
//exresult = result - ThirdNum;
}
if(operation.equals("*")){
result = FirstNum * SecondNum;
//exresult = result * ThirdNum;
}
if(operation.equals("/")){
result = FirstNum / SecondNum;
//exresult = result / ThirdNum;
}
screen.setText(String.valueOf(result));
//screen.setText(String.valueOf(exresult));
showtext.setText(String.valueOf(FirstNum + operation + SecondNum));
//showtext.setText(String.valueOf(FirstNum + operation + SecondNum +
operation + ThirdNum));
}
}
I guess you should do your calculations as double and then before setting the output to TextView (or whatever you are using), check for the output if int or not and then decide which form of output to set to the TextView.
if ((variable == Math.floor(variable)) && !Double.isInfinite(variable)) {
// integral type
}
See this
Edit:
The idea is to check that fractional part of the number is 0 (i.e.) the number is integer.
You may also Use these conditions [if true then variable is an Integer]
// check if
variable == Math.ceil(variable)
or
// check if
variable == Math.round(variable)
Also Math.round(float f) will return the interger form of the number!
To add multiple item first set up an array with a size of how long the user can input and then loop through each array adding them equivalently... i know this is a vague answer but you can ask me if anything is unclear and also an up vote would be nice. you got the right idea for the cases just try the following code
// array to sum
int[] numbers = new int[]{ 10, 10, 10, 10};
int sum = 0;
for (int i=0; i < numbers.length ; i++) {
sum = sum + numbers[i];
}
System.out.println("Sum value of array elements is : " + sum);
}

Button Print Toast When Clicked without answer Given

I have this button which calls two methods. See Code; Now i have tried to add a method on my onPictureSubmit(v) method which will print a Toast message (Please Submit Answer) if someone clicked the button without submitting an answer. Problem is it keeps crushing. Any help on how i can detect someone clicked the button without submitting answer will be appreciated.
My Button Code;
#Override
public void onClick(View v) {
switch (pass) {
case 0:
onDefinitionSubmit(v);
break;
case 1:
onPictureSubmit(v);
break;
case 2
break;
}
}
My Code :
private void onPictureSubmit(View v) {
if (v.getId() == R.id.picture_submit) {
final int answerGiven = Integer.parseInt("" + ((EditText) findViewById(R.id.picture_answer)).getText());
final int answerKey = com.madonasystematixnote.mathhelper.lessons.PictureFragment.answer;
final int x = Integer.parseInt("" + ((TextView) findViewById(R.id.picture_x)).getText());
final int y = Integer.parseInt("" + ((TextView) findViewById(R.id.picture_y)).getText());
}
}
If I were you I'd declare the TextView, EditText, Button as a global variable, and then in your onCreate() I'd use the findViewById() to avoid NullPointerException.
Second, I'd check if the answerGiven (I guess is the answer) it's empty, so I'd create a method that returns me if it's empty or not the EditText.
public boolean isEtEmpty(String str){
if(str.isEmpty() || str.length() == 0 || str.equals("") || str == null){
return true;
}
else{
return false;
}
}
Then at the time you call onPictureSubmit() call this method doing this :
if (v.getId() == R.id.picture_submit) {
if (isEtEmpty(picture_answer.getText())){ //picture_answer is the EditText that you want to know if it's empty or not
Toast.makeText(v.getContext(), "Please Submit Answer",Toast.LENGTH_LONG).show();
}
else{
final int answerGiven = Integer.parseInt("" + ((EditText) findViewById(R.id.picture_answer)).getText());
final int answerKey = com.madonasystematixnote.mathhelper.lessons.PictureFragment.answer;
final int x = Integer.parseInt("" + ((TextView) findViewById(R.id.picture_x)).getText());
final int y = Integer.parseInt("" + ((TextView) findViewById(R.id.picture_y)).getText());
}
}

generate next color randomly if the color is still available

I m working on an app for android and I'm struggling at some points. One of them would be to chose the next color (out of four) but keeping in mind, that the color chosen, could be empty already, in this case the next of the four colors shall be chosen
I have two ways of doing it, but one of them is way too much code and the other one is causing a crash (I guess that happens because it can end up in an endless loop)
Thanks in advance
public void nextColor(Canvas canvas) {
Random rnd = new Random(System.currentTimeMillis());
int theNextColor = rnd.nextInt(4);
switch (theNextColor) {
case 0:
if (!blue.isEmpty()) {
currentPaint = paintBlue;
} else
nextColor(canvas);
case 1:
if (!grey.isEmpty()) {
currentPaint = paintGray;
} else
nextColor(canvas);
case 2:
if (!gold.isEmpty()) {
currentPaint = paintGold;
} else
nextColor(canvas);
case 3:
if (!red.isEmpty()) {
currentPaint = paintRed;
} else
nextColor(canvas);
}
What happens if all four colors are chosen?
Regardless, this doesn't seem to be a situation where a recursive call is required. Try something like the following:
public void nextColor(Canvas canvas) {
Random rnd = new Random(System.currentTimeMillis());
int theNextColor;
boolean colorFound = false;
while (!colorFound) {
theNextColor = rnd.nextInt(4);
if (theNextColor == 0) {
currentPaint = paintBlue;
colorFound = true;
} else if (theNextColor == 1) {
currentPaint = paintGray;
colorFound = true;
} else if (theNextColor == 2) {
currentPaint = paintGold;
colorFound = true;
} else if (theNextColor == 3) {
currentPaint = paintRed;
colorFound = true;
}
}

Categories

Resources