-2

What I want to do is call a method which is placed in my MainActivity.java file from another subclass. But everytime i want to call this method, my app crashes.

I already tried to make SetGerateStat() static but that didn't change anything. Also, I can build the apk without any errors, the application only crashes when the SetGerateStat() is called from the Thread.

What am I doing wrong here?

My code is below (please note that this is only a snippet): MainActivity.java:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private CheckedTextView gerätestat;

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

public void setGeraeteStat(boolean x) {
    if (x==true) {
        gerätestat.setCheckMarkDrawable(android.R.drawable.presence_online);
    } else {
        gerätestat.setCheckMarkDrawable(android.R.drawable.presence_busy);
    }
}

public void onClick(View v) {
    if(v==button_refresh) {            
        Thread connection = new Thread(new Conn("refresh", MainActivity.this));
        connection.start();
    }
}

Conn.java:

public class Conn implements Runnable {
private MainActivity act;
private String actioncommand;

public Conn(String a) {
    actioncommand = a;
    act = null;
}

public Conn(String a, MainActivity m) {
    actioncommand = a;
    act = m;
}

public void run() {
     switch(actioncommand) {               
        case "refresh": {
            act.setGeraeteStat(true);                    
        }
        break;  
      }
}
Jas On
  • 51
  • 8

1 Answers1

0

Have you forgot to initialize gerätestat ? You have to initialize gerätestat after setcontentview. After that use runOnUIThread method as below

 public void setGeraeteStat(final boolean x){
 runOnUiThread (new Runnable() { 
     public void run() {
         if (x==true) {
          gerätestat.setCheckMarkDrawable(android.R.drawable.presence_online);
        } else {
         gerätestat.setCheckMarkDrawable(android.R.drawable.presence_busy);
        }
     }
 });}
Praveen
  • 697
  • 6
  • 21
  • gerätestat was initialized. I just didn't know that I had to use runOnUiThread, I thought I could just pass the activitiy as parameter. Thanks for your help :) – Jas On Sep 26 '16 at 13:18