从主要活动的方法不及格到其他活动 [英] Methods from main activity not passing into other activities

查看:203
本文介绍了从主要活动的方法不及格到其他活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图建立一个Q&安培;有一个活动,并且改变textviews,按钮,记分等我有一个setter和getter类多类A的应用程序。我的主要活动举办一个名为一套方法,它可为每个文本视图,按钮到适当的ID。当我尝试调用main.set();我得到的错误:

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

如果我这个类中的复制和粘贴set()方法到我MorseFalls类并调用设置()我没有得到这个错误。这使我相信,方法和变量没有得到传递到其他类。任何人都可以帮忙吗?我一直停留在这个超过5天,它击毁我的头。我将我的贴code为调用该方法集的主要和类:

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));
}

}

型号:

/**
 * 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;
}

}

推荐答案

当你做findViewById,与您要必须在被中的setContentView充气activity_main.xml中文件中定义的ID的看法。

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.

在您MorseFalls活动中,您通过新MainActivity创建MainActivity的新实例()。这仅仅是创建一个Java对象 - 它不会叫的onCreate。因此,activity_main.xml中并没有夸大你和意见不能被发现。现在,谁实际上是负责调用活动的生命周期方法,如的onCreate和的onDestroy?该系统将调用它,而不是你。

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.

在任何情况下,请不要认为的活动仅仅是另一个Java类。它是比这更。每个活动都必须在清单中声明,并且(例如,当用户最小化您的应用程序中,然后的onPause活性的onStop被自动调用),操作系统将处理活动的生命周期。应该不是在一般情况下,是活动之间通过引用prevent存储器的问题。你应该甚至不通过构造函数来实例化的活动。

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 (e.g. 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.

这篇关于从主要活动的方法不及格到其他活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆