简体   繁体   中英

Why does this create a FORCE CLOSE

public class MainClass extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Intent intent1 = new Intent(MainClass.this, SecondClass.class);
        startActivity(intent1);
    }

//---------------------------------------------
public class SecondClass extends Activity {
    ThirdClass thirdclass;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.keyboard);

        thirdclass.Random_Method('A');
    }

//---------------------------------------------
public class ThirdClass  extends Activity {
    public void Random_Method(char NewChar) {

    }

I see a couple possible problems:

  1. ThirdClass is never instantiated according to your code above.
  2. You're calling one Activity's function from another Activity. I don't think that's really possible the way the Android lifecycle works.

ThirdClass thirdclass was never initalized. Change the code to

thirdclass = new ThirdClass();
thirdclass.Random_Method(‘A’);

Or, alternatively, do this:

new ThirdClass().RandomMethod('A');

Also, ThirdClass does not need to extend Activity (and it shouldn't unless you can explain why it needs to).

EDIT:

If it does need to extend Activity then you should be switching to ThirdClass in the same way that MainClass switches to SecondClass with intents. Or rethink the way your activities work so that this TextView happens in SecondClass. The second would be done like:

public class SecondClass extends Activity {
    TextView textView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.keyboard);
        textView = (TextView) findViewById(R.id.something);
        random_Method('A');
    }

    public void random_Method(char NewChar) {

    }

ThirdClass hasn't been initialized. You will either need to make Random_Method static or use

thirdclass = new ThirdClass()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM