2014-02-08 3 views
0

Fragments를 사용하는 앱을 만들고 랩톱과 통신하는 클라이언트 스레드에서받은 메시지를 기반으로 TextView의 텍스트를 변경하려고합니다. 클라이언트 서버 통신은 문제가되지 않습니다. 클라이언트 스레드가 문자열을 정상적으로 수신하고 있기 때문입니다.다른 스레드에서 Fragment에 액세스하여 TextView 텍스트를 변경하려고합니다

파편 TextView에 액세스하고 텍스트를 변경하는 방법을 제대로 파악하지 못하는 것 같습니다. 여기 내가 현재 그렇게하려고하는 방법입니다 :이 경우

class ClientThread implements Runnable { 
    public void run() { 
      mHandler.post(new Runnable() { 
       @Override 
       public void run() { 
        LivingRoomFragment frag = (LivingRoomFragment)getSupportFragmentManager().findFragmentById(R.id.LivingRoomFragment); 
        frag.setText("Inside ClientThread right now"); 
       } 
      }); 
    } 
} 


public static class LivingRoomFragment extends Fragment { 
    public static final String ARG_SECTION_NUMBER = "section_number"; 
    TextView temp; 

    public LivingRoomFragment(){ 

    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.activity_room_control_fragment1, container, false); 
     temp = (TextView) rootView.findViewById(R.id.textView5); 
     MainActivity main = new MainActivity(); 
     new Thread(main.new ClientThread(requests)).start(); 
     return rootView; 
    } 

    public void setText(String s){ 
     temp.setText(s); 
    } 
} 

, MainActivity는 FragmentActivity을 확장 활동이다.

나는 에뮬레이터를 사용하고 있는데 응용 프로그램은 항상 frag.setText("Inside ClientThread right now")을 사용하는 줄에 null 포인터 예외가 있다고 말하면서 충돌합니다. 이는 LivingRoomFragment의 인스턴스가 null이라는 것을 의미합니다. 지금까지와 같은 방법을 사용하지 않고 스레드에서 UI에 액세스 할 수 없으므로 Handler를 사용하여이 메서드를 실행해야합니다.

내가 뭘 잘못하고 있니? 나는 확실하지 않다

+0

현재 단편과 통신하는 대신 단편의 새 인스턴스를 생성합니다. –

+0

좋아, 현재 조각과 어떻게 의사 소통을하니? 나는'getFragmentById()'가 현재 프래그먼트를 얻고 있다고 생각했지만, 실제로 그 프래그먼트 ID를 사용하여 새로운 인스턴스를 만드는 것이 무엇인지 생각해 본다. – Toast

+0

정확합니다. ID를 사용하는 것은 처음에 LivingRoomFragment를 Fragment manager로 커밋 할 때 태그를 설정하여 null 인 새 인스턴스를 만들고있었습니다. 나중에'.getFragmentByTag (tag) '를 사용하여 해당 조각에 액세스 할 수 있습니다. – Toast

답변

0

,

MainActivity main = (MainActivity)getActivity; 

대신

MainActivity main = new MainActivity(); 
+0

그래도 여전히'frag.setText()'는 nullPointerException를 준다. – Toast

0

좋아 토스트보십시오. 이제 해결책이 있습니다.

조각에 브로드 캐스트 수신기를 만듭니다. 액션을 생성하려면 액션은 방송을 다른 사람에게 알리는 열쇠입니다. 예제 코드 아래

사용. (당신이 후 더 많은 코드가없는, 그래서 당신이 좋아 싶지 않을 수도 있습니다 ecxatly 무엇을?)

class ClientThread implements Runnable { 
    private Handler mHandler; 

    public void run() { 
     mHandler.post(new Runnable() { 
      @Override 
      public void run() { 

       Intent intent = new Intent("my_action"); 
       intent.putExtra("message", "TEXT_YOU_WANT_TO_SET"); 
       sendBroadcast(intent); 
       // LocalBroadcastManager manager = LocalBroadcastManager 
       // .getInstance(context); 
       // LivingRoomFragment frag = (LivingRoomFragment) 
       // getSupportFragmentManager() 
       // .findFragmentById(R.id.LivingRoomFragment); 
       // frag.setText("Inside ClientThread right now"); 
      } 
     }); 
    } 
} 

public static class LivingRoomFragment extends Fragment { 
    public static final String ARG_SECTION_NUMBER = "section_number"; 
    TextView temp; 
    private MyBroadCastReceiver broadCastReceiver; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     broadCastReceiver = new MyBroadCastReceiver(); 
     getActivity().registerReceiver(broadCastReceiver, 
       new IntentFilter("my_action")); 
    } 

    public LivingRoomFragment() { 

    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     View rootView = inflater.inflate(
       R.layout.activity_room_control_fragment1, container, false); 
     temp = (TextView) rootView.findViewById(R.id.textView5); 
     MainActivity main = new MainActivity(); 
     new Thread(main.new ClientThread(requests)).start(); 
     return rootView; 
    } 

    public void setText(String s) { 
     temp.setText(s); 
    } 

    private class MyBroadCastReceiver extends BroadcastReceiver { 

     @Override 
     public void onReceive(Context arg0, Intent intent) { 
      // chaneg the TextView text here 
      if (intent.getAction() != null 
        && intent.getAction().equalsIgnoreCase("my_action")) { 
       temp.setText(intent.getStringExtra("message")); 
      } 
     } 

    } 

} 

행운을 빕니다.

관련 문제