简体   繁体   中英

Methods from main activity not passing into other activities

I am trying to develop a Q&A app that has one activity and multiple classes that alter textviews, buttons, score, etc. I have a setter and getter class. My main activity hold a method called set that assigns each text view, buttons to their appropriate ID's. When I try to call the main.set(); I get the error :

java.lang.NullPointerException: Attempt to invoke virtual method
'android.view.View android.view.Window.findViewById(int)' on a null object
reference

If I copy and paste the set() method into my MorseFalls class and call set() within that class I don't get the error. This leads me to believe that methods and variables aren't getting passed into other classes. Can anyone help? I have been stuck on this for over 5 days and it's wrecking my head. I will paste my code for the main and class that is calling the set method:

public class MainActivity extends AppCompatActivity {


public static Model model = new Model();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    set();
    beginMorse();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}



//Which scale to go to next (if true means selected)
public void scale(){
    //not relevant
}

//Morse Falls
public void beginMorse() {
    // Start intent here
    Intent intent = new Intent(this, MorseFalls.class);
    intent.putExtra("intVariableName", 0);
    startActivity(intent);
}


public void set(){
    model.setT((TextView) findViewById(R.id.Question));
    model.setA((TextView) findViewById(R.id.AnswerA));
    model.setB((TextView) findViewById(R.id.AnswerB));
    model.setC((TextView) findViewById(R.id.AnswerC));
    model.setD((TextView) findViewById(R.id.AnswerD));
    model.setCs((TextView) findViewById(R.id.currentscore));
    model.setScore((TextView) findViewById(R.id.Score));
    model.setUnticked((TextView) findViewById(R.id.please_answer));
    model.setCC((TextView) findViewById(R.id.Answer2C));
    model.setDD((TextView) findViewById(R.id.Answer2D));
    model.setE((TextView) findViewById(R.id.AnswerE));
    model.setF((TextView) findViewById(R.id.AnswerF));
    model.setG((TextView) findViewById(R.id.AnswerG));
    model.setH((TextView) findViewById(R.id.AnswerH));
    model.setMyVib((Vibrator) this.getSystemService(VIBRATOR_SERVICE));
    model.setB((Button) findViewById(R.id.button));
    model.setNext_test((Button) findViewById(R.id.Next_Test));
    model.setR((RadioGroup) findViewById(R.id.radioGroup));;
    model.setOldpatient((Button) findViewById(R.id.oldtest));
    model.setNewpatient((Button) findViewById(R.id.newtest));
}

}

/**
 * Morse Falls scale
 */
public class MorseFalls extends AppCompatActivity{



private Model model = MainActivity.model;
private MainActivity main = new MainActivity();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    //passing intent
    Intent mIntent = getIntent();

    //ERROR LIES HERE
    main.set();
    //set();
    declaration();

    model.getCC().setVisibility(View.GONE);
    model.getDD().setVisibility(View.GONE);
    findViewById(R.id.button).setVisibility(View.VISIBLE);

    //Morse Falls question one
    questionOne();
    PreviousScore = score;
    //button listener, when button clicked, produce output on textfield "Score"
    model.getButton().setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            model.getMyVib().vibrate(70);
            PreviousScore = score;

            //Score.setText(String.valueOf(action()));
            model.getScore().setText(String.valueOf(score));
            model.getCs().setText(String.valueOf(score));
            i++;

            //If answer not selected display "Please select answer
            if (model.getR().getCheckedRadioButtonId() == -1) {
                model.getUnticked().setVisibility(View.VISIBLE);
                model.getUnticked().setText("Please Select An Answer");
            } else {
                //Loop through questions
                if (i == 1)
                    questionOne();
                if (i == 2)
                    questionTwo();
                if (i == 3)
                    questionThree();
                if (i == 4)
                    questionFour();
                if (i == 5)
                    questionFive();
                if (i == 6)
                    questionSix();
                if (i == 7)
                    MorseFinish();
            }

            //For testing purpose keep displaying score after each answer
            model.getR().clearCheck();
            model.getCs().setText("Current Score: " + String.valueOf(score));

        }

    });

    //set Morse to false then call scalr question which shows which scale to complete next
    model.getNext_test().setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            model.getMyVib().vibrate(70);
            main.Morse = false;
            main.scale();
        }

    });

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

//declaring buttons visible and their text
private void declaration(){
    //not relevant
}


//scoring system
public void onRadioButtonClicked(View view) {
    //not relevant
        }
}

/*
Questions
 */
private void questionOne(){
    //not relevant
}

private void questionTwo(){
    //not relevant
}

private void questionThree(){
    //not relevant
}

private void questionFour(){
    //not relevant
}

private void questionFive(){
    //not relevant
}

private void questionSix(){
    //not relevant
}

//Display Morse Score and show advance button
private void MorseFinish(){
    model.getA().setVisibility(View.GONE);
    model.getB().setVisibility(View.GONE);
    model.getT().setText("Final Morse Score");
    model.getNext_test().setVisibility(View.VISIBLE);
    model.getScore().setVisibility(View.VISIBLE);
    model.getButton().setVisibility(View.VISIBLE);

}


public void set(){
    model.setT((TextView) findViewById(R.id.Question));
    model.setA((TextView) findViewById(R.id.AnswerA));
    model.setB((TextView) findViewById(R.id.AnswerB));
    model.setC((TextView) findViewById(R.id.AnswerC));
    model.setD((TextView) findViewById(R.id.AnswerD));
    model.setCs((TextView) findViewById(R.id.currentscore));
    model.setScore((TextView) findViewById(R.id.Score));
    model.setUnticked((TextView) findViewById(R.id.please_answer));
    model.setCC((TextView) findViewById(R.id.Answer2C));
    model.setDD((TextView) findViewById(R.id.Answer2D));
    model.setE((TextView) findViewById(R.id.AnswerE));
    model.setF((TextView) findViewById(R.id.AnswerF));
    model.setG((TextView) findViewById(R.id.AnswerG));
    model.setH((TextView) findViewById(R.id.AnswerH));
    model.setMyVib((Vibrator) this.getSystemService(VIBRATOR_SERVICE));
    //model.setB((Button) findViewById(R.id.button));
    model.setNext_test((Button) findViewById(R.id.Next_Test));
    model.setR((RadioGroup) findViewById(R.id.radioGroup));
    model.setCheckTinetti((CheckBox) findViewById(R.id.checkTinetti));
    model.setCheckEfficacy((CheckBox) findViewById(R.id.checkEfficacy));
    model.setCheckFRAT((CheckBox) findViewById(R.id.checkFRAT));
    model.setCheckMorse((CheckBox) findViewById(R.id.checkMorse));
    model.setOldpatient((Button) findViewById(R.id.oldtest));
    model.setNewpatient((Button) findViewById(R.id.newtest));
    model.setButton((Button) findViewById(R.id.button));
}

}

Model:

/**
 * Created by user on 07/03/2016.
 */
public class Model extends AppCompatActivity {

public static Vibrator myVib;
public static TextView T, A, B, C, D, E, F, G, H, CC, DD, cs, score, unticked;
public static Button next_test, button, newpatient, oldpatient;
public static RadioGroup r;
public static CheckBox checkTinetti, checkEfficacy, checkFRAT, checkMorse;

public static Vibrator getMyVib() {
    return myVib;
}

public static void setMyVib(Vibrator myVib) {
    Model.myVib = myVib;
}

public static TextView getT() {
    return T;
}

public static void setT(TextView t) {
    T = t;
}

public static TextView getA() {
    return A;
}

public static void setA(TextView a) {
    A = a;
}

public static TextView getB() {
    return B;
}

public static void setB(TextView b) {
    B = b;
}

public static TextView getC() {
    return C;
}

public static void setC(TextView c) {
    C = c;
}

public static TextView getD() {
    return D;
}

public static void setD(TextView d) {
    D = d;
}

public static TextView getE() {
    return E;
}

public static void setE(TextView e) {
    E = e;
}

public static TextView getF() {
    return F;
}

public static void setF(TextView f) {
    F = f;
}

public static TextView getG() {
    return G;
}

public static void setG(TextView g) {
    G = g;
}

public static TextView getH() {
    return H;
}

public static void setH(TextView h) {
    H = h;
}

public static TextView getCC() {
    return CC;
}

public static void setCC(TextView CC) {
    Model.CC = CC;
}

public static TextView getDD() {
    return DD;
}

public static void setDD(TextView DD) {
    Model.DD = DD;
}

public static TextView getCs() {
    return cs;
}

public static void setCs(TextView cs) {
    Model.cs = cs;
}

public static TextView getScore() {
    return score;
}

public static void setScore(TextView score) {
    Model.score = score;
}

public static TextView getUnticked() {
    return unticked;
}

public static void setUnticked(TextView unticked) {
    Model.unticked = unticked;
}

public static Button getNext_test() {
    return next_test;
}

public static void setNext_test(Button next_test) {
    Model.next_test = next_test;
}

public static Button getButton() {
    return button;
}

public static void setButton(Button button) {
    Model.button = button;
}

public static Button getNewpatient() {
    return newpatient;
}

public static void setNewpatient(Button newpatient) {
    Model.newpatient = newpatient;
}

public static Button getOldpatient() {
    return oldpatient;
}

public static void setOldpatient(Button oldpatient) {
    Model.oldpatient = oldpatient;
}

public static RadioGroup getR() {
    return r;
}

public static void setR(RadioGroup r) {
    Model.r = r;
}

public static CheckBox getCheckTinetti() {
    return checkTinetti;
}

public static void setCheckTinetti(CheckBox checkTinetti) {
    Model.checkTinetti = checkTinetti;
}

public static CheckBox getCheckEfficacy() {
    return checkEfficacy;
}

public static void setCheckEfficacy(CheckBox checkEfficacy) {
    Model.checkEfficacy = checkEfficacy;
}

public static CheckBox getCheckFRAT() {
    return checkFRAT;
}

public static void setCheckFRAT(CheckBox checkFRAT) {
    Model.checkFRAT = checkFRAT;
}

public static CheckBox getCheckMorse() {
    return checkMorse;
}

public static void setCheckMorse(CheckBox checkMorse) {
    Model.checkMorse = checkMorse;
}

}

I don't understand what you wan't to do. You shouldn't pass reference of views in one activity to another activity or make the reference to views static . The lifecycle of activities are handled by the operating system and after onDestroy has been called on an activity, its object could be garbage collected (Thats why you are getting null pointer exceptions).

When you do findViewById, the view with the id that you want must have been defined in the activity_main.xml file that was inflated during setContentView.

In your MorseFalls activity, you created a new instance of MainActivity via new MainActivity(). This is merely creating a Java object - it will NOT call onCreate. Hence the activity_main.xml was not inflated for you and the views can't be found. Now, who's actually responsible for calling the activity's lifecycle methods like onCreate and onDestroy? The system will call it, not you.

In any case, please do not think of activities as merely another Java class. It is more than that. Each activity must be declared in the manifest and the OS will handle the lifecycle of the activities (eg when the user minimizes your app, the onPause then onStop of the activity is called automatically). You should not, in general, be passing references between activities to prevent memory problems. You should not even be instantiating activities via the constructor.

If you want to re-use methods, put them in a separate class that does not extend from any activity. Also, each activity should have its own layout file and thus its own views, so there should be little reason to re-use methods that operate on the exactly same layout file and hence the same views.

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