-2

I'm trying to change the text in my TextView by using the setText().

When I try to do this I get the following error:

E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{<bla bla bla>}: java.lang.NullPointerException

Caused by: java.lang.NullPointerException
            at com.training.mytraining.test.MainActivity.display(MainActivity.java:35)

MainActivity.java

public class MainActivity extends AppCompatActivity {
TextView tvCountry;
private Server theServer;


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

    tvCountry = (TextView) findViewById(R.id.countryTextView);


    theServer = new Server(this);
    theServer.weatherFromYahoo();


}


public void display() {

    tvCountry.setText("USA");
}


}

Server.java

public class Server extends AppCompatActivity {
MainActivity theMainActivity;

//Constructor
public Server (Context context){
    this.theMainActivity = new MainActivity();
}

public void weatherFromYahoo() {

    theMainActivity.display();
}

}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<TextView
    android:id="@+id/countryTextView"
    android:text="@string/hello_world"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

This is just an example of my real code. I did'nt want to put all the code, so I made a new code with just that problem I get. I have to set the text by calling my MainActivity from an another class.

Please help me, I have been stuck here for hours.

ivan_pozdeev
  • 28,628
  • 13
  • 85
  • 130
btag
  • 17
  • 7

1 Answers1

0

Change this:

public Server (Context context){
    this.theMainActivity = new MainActivity();
}

To this:

public Server (Context context){
    this.theMainActivity = (MainActivity)context;
}

So that the onCreate is called properly still. If you are new'ing up an activity, it won't be able to set the view properly and follow the correct lifecycle. As @CommonsWare says, you shouldn't ever create an activity via its constructor.

jyanks
  • 2,266
  • 1
  • 17
  • 36