Bluel3ull Bluel3ull - 4 months ago 8
Android Question

Android| How would I write this code to be more Object orientated?

Hello I'm trying to use if statements to lunch different activity's. The following code does not seem very Object orientated. Does any one know a way in which I can make this more opp with out getting the error ("Variable intent may have not been initialized")

if (view.getId() == R.id.loadExistingBuildButton) {
intent = new Intent(this, LoadExistingBuildActivity.class);
startActivity(intent);
} else if (view.getId() == R.id.createNewBuildButton)
intent = new Intent(this, CreateNewBuildActivity.class);
startActivity(intent);
}

Answer
int id = view.getId();
if (id == R.id.loadExistingBuildButton) 
    startActivity(new Intent(this, LoadExistingBuildActivity.class);
else if (id == R.id.createNewBuildButton)
   startActivity(new Intent(this, CreateNewBuildActivity.class));

You can add an else statement for a default case.

If you end up with a lot of if/else ifs you could consider using a method like

public void runIntentActivity(Activity someName)
{
      startActivity(new Intent(this, someName.class ));
}

so you can call

 runIntentActivity(LoadExistingBuildActivity)

instead of

 startActivity(new Intent(this, LoadExistingBuildActivity.class);

for each if/elseif