Eli Eli - 6 months ago 19
Android Question

Need help changing Java code into a method addText (String text)

I have a homework assignment for my study Android application development that I need help with, I am only a beginner.
In my code (I did not write it, its a part of the study) in the methods onCreate, onSrart, onRestart, onResume, onPause, onStop I repeat the following line each time:

ausgabe += "First Activity - \"onStart\" durchlaufen\"n;

tvAnzeige.setText(ausgabe);


My assignment is to store these two lines in a method addText(String text) so that each time I will only invoke this method instead of using the repetition.
My question is how do I do this? A pseudocode will be very helpful.
I thank you in advance for any help or information and here is my code:

public class FirstActivity extends Activity
{
private String ausgabe = "";
public TextView tvAnzeige;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
Button button = (Button) this.findViewById(R.id.second_activity);
button.setOnClickListener(new ButtonOnClickListener());
tvAnzeige = (TextView) this.findViewById(R.id.anzeige);
ausgabe += "FirstActivity - \"onCreate\" durchlaufen\n";
tvAnzeige.setText(ausgabe);
}

@Override
protected void onStart()
{
super.onStart();
ausgabe += "FirstActivity - \"onStart\" durchlaufen\n";
tvAnzeige.setText(ausgabe);
}

@Override
protected void onResume()
{
super.onResume();
ausgabe += "FirstActivity -\"onResume\" durchlaufen\n";
tvAnzeige.setText(ausgabe);
}

@Override
protected void onPause()
{
super.onPause();
ausgabe += "FirstActivity -\"onPause\" durchlaufen\n";
tvAnzeige.setText(ausgabe);
}

@Override
protected void onStop()
{
super.onStop();
ausgabe += "FirstActivity -\"onStop\" durchlaufen\n";
tvAnzeige.setText(ausgabe);
}

@Override
protected void onRestart()
{
super.onRestart();
ausgabe += "FirstActivity -\"onRestart\" durchlaufen\n";
tvAnzeige.setText(ausgabe);
}

//inner listener class
class ButtonOnClickListener implements OnClickListener
{
@Override
public void onClick(View view)
{
ausgabe += "Button \"second Activity\" geklickt\n";
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
try
{
FirstActivity.this.startActivity(intent);
} catch (ActivityNotFoundException anfe)
{
ausgabe += anfe.toString() + "\n";
tvAnzeige.setText(ausgabe);
}
}
}
}

mjn mjn
Answer

Try something like this:

    @Override
    protected void onStart()
    {
        super.onStart();
        addText("FirstActivity - \"onStart\" durchlaufen\n");
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        addText("FirstActivity -\"onResume\" durchlaufen\n");
    }

    ... (more methods) 


    void addText(final String text) {
        ausgabe += text;
        tvAnzeige.setText(ausgabe);
    }