2011-02-24 9 views
0

私はスレッドとハンドラをアンドロイドで使用しています。アプリケーションは、私が活動の外から何の機能も持っていない限り正常に動作します。しかし、もし私がスレッドの中からアクティビティの外からいくつかのfuncyを呼び出すと、NullPointerExceptionが返されます。内部スレッドまたはasyntaskからの呼び出し禁止関数

package com.prog; 

import com.API.TextBoxCheck; 

import android.app.Activity; 
import android.app.ProgressDialog; 
import android.os.Bundle; 
import android.os.Handler; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 

public class ProgressBarExample extends Activity { 
    private Handler handler = new Handler(); 
    int i; 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 


     Button btn=(Button)findViewById(R.id.button1); 
     btn.setOnClickListener(new OnClickListener(){ 
      TextView tv=(TextView)findViewById(R.id.textView1); 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 

       Thread thread = new Thread(null, doBackgroundThreadProcessing, 
       "Background"); 
       thread.start(); 
      }}); 
     Button stopBtn=(Button)findViewById(R.id.button2); 
     stopBtn.setOnClickListener(new OnClickListener(){ 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 
      finish(); 
      }}); 
    } 

    private Runnable doBackgroundThreadProcessing = new Runnable() { 
    public void run() { 
    try { 
     backgroundThreadProcessing(); 
    } catch (InterruptedException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    } 
    }; 

    private void backgroundThreadProcessing() throws InterruptedException { 

     TextView tv=(TextView)findViewById(R.id.textView1); 

     i=0; 
     while(i<100) 
     { 
      handler.post(doUpdateGUI); 
     Thread.sleep(50); 

     i++;  
     } 
     EditText et=(EditText)findViewById(R.id.editText1); 

     TextBoxCheck tbc = new com.API.TextBoxCheck(); 
     String reply=tbc.TextBoxChecker(et.getText().toString(),10); 
     Log.d("thread", reply); 
    } 


    private Runnable doUpdateGUI = new Runnable() { 
    public void run() { 
    updateGUI(); 
    } 

    private void updateGUI() { 
     // TODO Auto-generated method stub 
     TextView tv=(TextView)findViewById(R.id.textView1); 
     tv.setText(i+"%"); 

    } 
    }; 
} 

私はtextBoxCheck becozのコードを削除しました。ここでは不必要であると思います。 これを手伝ってください。

PS。私もAsyncTaskを使ってみましたが、同じ問題が発生します。

答えて

1

あなたはUIスレッドではありません。 UI項目を操作するには、UIスレッドを使用する必要があります。 UIスレッドでハンドラを作成し、backgroundThreadProcessing()を呼び出します。ハンドラからではなく、UI以外のスレッドからではありません。

関連する問題