2011-02-24 17 views
0

我在android中使用線程和處理程序。該應用程序工作正常,只要我沒有任何外部活動的功能。但是如果我從線程內部的活動外部調用一些funcyion,它會給出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線程。