想不到今天讓我遇到一個難解的問題,
趕快分享給各位:
package com.example.testui; import java.io.IOException; import java.net.MalformedURLException; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity { Handler handler; Runnable r = new Runnable(){ @Override public void run() { Message msg = handler.obtainMessage(); Bundle b = new Bundle(); // for some reason you have put another thread to get data from net // your code here than get data 位置有差喔!!! //facebook 在某些 android 版本會NetworkOnMainThreadException error 解法是 在另一個Thread上跑 為了解這個問題 所以用了 這個架構,結果找到更多問題! fb.request("https://graph.facebook.com/me");b.putString("me", "yaya"); msg.setData(b); handler.sendMessage(msg); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button b = (Button)findViewById(R.id.button1); b.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { // TODO Auto-generated method stub new Thread(r ).start(); //因為onclick..是子線程,android有限制這裡 new thread 不能在更動 UI ! } }); Looper looper = Looper.getMainLooper(); //一定得取得 main looper handler = new Handler(looper){ public void handleMessage(Message msg) { //String me = msg.getData().getString("me"); TextView t = (TextView)findViewById(R.id.text); t.setText(msg.getData().get("me").toString()); } }; } }
沒有留言:
張貼留言