开发者

android Thread Textviev write problem

开发者 https://www.devze.com 2023-02-16 22:43 出处:网络
İ want to write textview a simple word via Thread but it is force close codes is that : package thread.denemesi;

İ want to write textview a simple word via Thread but it is force close

codes is that :

package thread.denemesi;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class baslat extends Activity {
   Button buton1,buton2;
   Thread thread2,thread1;
   TextView yazi;
   int sayi=0;
   ArrayList<Integer> dizi;
   int sayac=0;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        buton1=(Button)findViewById(R.id.button1);
        buton2=(Button)findViewById(R.id.button2);
        yazi=(TextView)findViewById(R.id.textview);
        dizi=new ArrayList<Integer>();



        buton1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                thread1=new Thread(new Runnable() {

                    @Override
                    public void run() {
                //      for (int i = 0; i < 100; i++) {
                    //      dizi.add(i);


                //      }   
                        for开发者_如何学Go (int i = 0; i < 10; i++) {

                            sayac++;
                            try {
                                yazi.setText("i want to write a word");
                                Thread.sleep(100);

                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }

                        }               
                    }); 
                thread1.start();
            }
        });




    }


First, you should have used adb logcat, DDMS, or the DDMS perspective in Eclipse to examine LogCat and look at the stack trace associated with your "force close".

You would find that your exception is something like "Attempted to modify the UI from a non-UI thread".

You will need to call setText() from the main application thread, not your background thread. You can do this via:

  • a Handler
  • calling post() on your TextView, passing a Runnable
  • calling runOnUiThread() on your Activity, passing a Runnable
0

精彩评论

暂无评论...
验证码 换一张
取 消