Home > Mobile >  Calling data from model class in android
Calling data from model class in android

Time:08-29

MainActivity

public class MainActivity extends AppCompatActivity {

    // Button
    private Button button;

    // TextView
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ModelClass modelClass = new ModelClass();
        modelClass.setTest("Sung Sikyung");

        // TextView
        textView = findViewById(R.id.textView);
        textView.setText(modelClass.getTest());

        // Button
        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(getBaseContext(), SubActivity.class);
                startActivity(intent);
            }
        });
    }
}

I tried to set data in ModelClass, and get it to set TextView Text. but npe occurred. How can I call model class' data, and set it as a textView text?

CodePudding user response:

I have gone through your code, I hope your model class 'ModelClass' is as follows,

public class ModelClass {

public String test;

public ModelClass() {
}

public String getTest() {
    return test;
}

public void setTest(String test) {
    this.test = test;
}}

and your main activity is as follows,

public class MainActivity extends AppCompatActivity {

private TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ModelClass modelClass = new ModelClass();
    modelClass.setTest("Sung Sikyung");

    // TextView
    textView = findViewById(R.id.textView);
    textView.setText(modelClass.getTest());

}}

I haven't implemented the button but the code works just fine. Data from the model class is displayed in the textView. If you have any doubt, please add some more details to your question.

Output screen

Thank you.

  • Related