2011-08-11 10 views
0

어떻게 스레드 내부의 클래스 수준 변수에 액세스 할 수 있습니까? 직접 변수에 액세스하려고 시도했지만 예외가 발생했습니다. 스레드 내에서 클래스 수준 변수에 액세스 할 수 있습니까 또는 처리기를 사용해야합니까?스레드의 클래스 수준 변수 액세스

다음은 나의 코드입니다.

public class MainMapActivity extends MapActivity 
     {  
      //*************************************************************************************** 
      //isRouteDisplayed Method (Override) 
      @Override 
      protected boolean isRouteDisplayed() 
      { 
       return false; 
      }//End method 
      //*************************************************************************************** 
      //private Handler handlerTimer = new Handler(); 

      //*************************************************************************************** 
      //Class Level Variables & Objects 

      String[] Device_ID = null; 

      //*************************************************************************************** 
      //onCreate method (Override the built-in method) Called when the activity is first created. 
      @Override 
      public void onCreate(Bundle savedInstanceState) 
      { 

       //handlerTimer.removeCallbacks(taskUpdateStuffOnDialog); 
       //handlerTimer.postDelayed(taskUpdateStuffOnDialog , 100); 


       //service = new NewService(); 

       new Thread(taskUpdateStuffOnDialog).start(); 
       // GIve the Server some time for startup 
       try 
       { 
         Thread.sleep(500); 
       } 
       catch (InterruptedException e) 
       { 

       } 

       // Kickoff the Client 
       // startService(new Intent(this, NewService.class)); 
       new Thread(new NewService()).start(); 



      }//End onCreate 
      //*************************************************************************************** 

      private Runnable taskUpdateStuffOnDialog = new Runnable() 
      { 

       public void run() 
       { 
        GlobalVariable appState = ((GlobalVariable)getApplicationContext()); 
        try 
        { 
         serverAddr = InetAddress.getByName(SERVERIP); 
         Log.d("UDP", "S: Connecting..."); 
         /* Create new UDP-Socket */ 
         socket = new DatagramSocket(SERVERPORT, serverAddr); 

        } 
        catch (Exception e) 
        { 
         Log.e("UDP", "S: Error", e); 

        } 

        while(true) 
        { 
          // TODO Auto-generated method stub 
          try 
          { 
             /* Retrieve the ServerName */ 
             /* By magic we know, how much data will be waiting for us */ 
             byte[] buf = new byte[72]; 
             /* Prepare a UDP-Packet that can 
             * contain the data we want to receive */ 

             DatagramPacket packet = new DatagramPacket(buf, buf.length); 
             Log.d("UDP", "S: Receiving..."); 


             /* Receive the UDP-Packet */ 
             socket.receive(packet); 

             String id = new String(packet.getData()); 

             //buffer.order(ByteOrder.LITTLE_ENDIAN); // if you want little-endian 



             String[] tokens = id.split(" "); 
             String b = tokens[0]; 

             Log.d("Message: ", b + " " ); 
           /***************************** sending device ID *************************************/ 


           else if(b.equals("5")) 
           { 
            Device_ID[0] = tokens[1]; 

            runOnUiThread(new Runnable() 
            { 
             public void run() 
             { 

              String id = tokens[1]; 
              Log.d("UDP", "S: Received Device ID: '" + id + "'"); 


              setID(id); 
              //positionOverlay.setID(id); 
              //addEvent(id); 
              Toast.makeText(MainMapActivity.this, "Your Device ID " + id,Toast.LENGTH_LONG).show(); 
             } 
            }); 
            //Toast.makeText(MainMapActivity.this, "Your Device ID " + b,Toast.LENGTH_LONG).show(); 

           } // end else if 


          } // end try 
          catch (Exception e) 
          { 
           Log.e("UDP", "S: Error", e); 
          } // end catch 

          //handlerTimer.postDelayed(this, 100); 
         } // end while condition 
        //*************************************************************************************** 
        }//End Run method 
       //*************************************************************************************** 
      };//End Thread 
      //*************************************************************************************** 




} 

예외는이 줄에서 Device_ID[0] = tokens[1]; 의 널 포인터 예외입니다. 그래서 당신은 분명 널 포인터 예외 나 구문 적으로 유효한 자바처럼 보이지 않는

+0

"예외가 발생했습니다"는 우리에게 유용한 정보를 제공하지 않습니다. http://tinyurl.com/so-hints를 읽고 이에 맞게 질문을 편집하십시오. –

+0

코드 스 니펫은 토큰이 선언 된 위치, 초기화 된 위치 만 표시합니다. – shelley

답변

2

를 얻을 -

+0

이것은 전체 코드가 아니며 곧 데모 용으로 작성했습니다. 컴파일 시간 오류가 없습니다. – Siddiqui

+0

지금 확인하십시오. – Siddiqui

+0

고마워, 너의 요점이있어. – Siddiqui

-1

당신의 DeviceID은 [] 널 (null)을 제외하고 아무것도 배열을 초기화하지 않을 것으로 보인다. ClassToken = token;이 인식되지 않는다는 컴파일 오류가 발생했습니다. 그리고 그걸 지나면, 당신이 run() 방법을 선언하지 않았다는 또 다른 말입니다. 그리고 세미콜론이 없습니다. 오류를 주시는 실제 코드를 게시하는 걱정한다면


, 우리는 실제 문제가 무엇인지를 말할 수 있습니다.


문제

는 오히려 배열보다 nullDevice_ID를 초기화 한 것입니다. null을 색인하려고하면 NPE가 표시됩니다.

간단한 수정을 초기화 변경하는 것입니다. 주어진 코드에서 당신이 전혀 배열을 사용해야하는 이유

String[] Device_ID = new String[1]; 

(내가 볼 수 없습니다를 왜 그냥 Device_IDString을 ? OTOH, 아마도 이것은 단지 당신의 데모 코드의 인공물 일뿐입니다 ...)

관련 문제