2017-07-10 10 views
-1

子スレッドからのビューアイテムのコントロールを理解するために、アプリケーションをAndroidに書き込みました。メインルーパーをMainactivityという名前から取り出し、コンストラクターを介して子スレッドを実装するクラスに渡し、コールバックを介してTextViewの内容を変更するだけです。ハンドラを作成する前にアプリケーションは、セカンダリスレッドハンドラが作成された場所に残ります

public class MainActivity extends AppCompatActivity { 
private TextView textView = null; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Log.i("create", Thread.currentThread().toString()); 
    textView = (TextView) findViewById(R.id.textView); 
    HandlerTextView handlerTextView = new HandlerTextView(getApplicationContext().getMainLooper()); 
    handlerTextView.registerMessage(new Message() { 
     @Override 
     public void handleMessage(String msg) { 
      textView.setText(msg); 
     } 
    }); 
    HandlerThread handlerThread = new HandlerThread("two", HandlerThread.NORM_PRIORITY); 
    if(handlerThread != null){ 
     Handler a = new Handler(handlerThread.getLooper()); 
     if(a != null) { 
      a.post(handlerTextView); 
     } 
    } 
    } 
} 

public class HandlerTextView implements Runnable { 

private Looper mainLooper = null; 
private TextView textView = null; 
private Socket socket = null; 
private Message message = null; 

public HandlerTextView(Looper looper) { 
    this.mainLooper = looper; 
} 

public void registerMessage(Message m) { 
    this.message = m; 
} 

private void setText(final String str) { 
    Handler handler = new Handler(mainLooper); 
    handler.post(new Runnable() { 
     @Override 
     public void run() { 
      message.handleMessage(str); 
     } 
    }); 
} 

@Override 
public void run() { 
    setText("dfsdfsdfsdf"); 
    } 
} 

Created a new Handlerthread thread handler object, took it looper and passed it to the constructor of the new handler handler and it The error: FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{elaneturn.com.myapplication/elaneturn.com.myapplication.MainActiv Caused by: java.lang.NullPointerException

答えて

0

コールhandlerThread.start():

handlerThread.start(); 
Handler a = new Handler(handlerThread.getLooper()); 
+0

はどうもありがとうございました! –

関連する問題