1

XAMPP 서버에 연결하고 아래 클래스로 MySQL 데이터베이스와 상호 작용하려고합니다. 그러나이 줄에 NullPointerException이 수신되었다는 오류 메시지가 표시됩니다.NullPointerError : 서버에 연결할 수 없습니다.

result = imService.createNewGroup(newGroupName); 

CreateGroup 클래스에서. CreateGroup 클래스는 사용자가 Dialog에 텍스트를 입력하고 거기에서 서비스가 시작된 직후에 호출된다는 점에 유의해야합니다. 나는 서비스와 네트워크 연결에 대해 상당히 새로운 것이지만 적어도 .createGroup 명령을 보내려고하기 전에 서비스가 연결되어 있는지 확인할 수 있어야만하는 것이있다.

이 createGroup 클래스 : "이 createGroup"방법

public class CreateGroup extends Activity { 

    private static final String SERVER_RES_RES_SIGN_UP_SUCCESFULL = "1"; 
    private static final String SERVER_RES_SIGN_UP_USERNAME_CRASHED = "2"; 

    private Manager imService; 
    private Handler handler = new Handler(); 
    String newGroupName; 

    public ServiceConnection mConnection = new ServiceConnection() { 

     public void onServiceConnected(ComponentName className, IBinder service) { 
      imService = ((MessagingService.IMBinder) service).getService(); 

     } 

     public void onServiceDisconnected(ComponentName className) { 

      imService = null; 
      Toast.makeText(CreateGroup.this, R.string.local_service_stopped, 
        Toast.LENGTH_SHORT).show(); 
     } 
    }; 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     bindService(new Intent(CreateGroup.this, MessagingService.class), 
       mConnection, Context.BIND_AUTO_CREATE); 

     // Getting intent and info from the dialog 
     Intent i = getIntent(); 
     Bundle extras = i.getExtras(); 

     newGroupName = extras.getString("groupName"); 

     Thread thread = new Thread() { 
      String result = new String(); 

      @Override 
      public void run() { 

       // Send group name to the messaging 
       // service 
       try { 
        result = imService.createNewGroup(newGroupName); 

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

       Log.d("problem", "The value of result is " + result.toString()); 

       handler.post(new Runnable() { 

        @Override 
        public void run() { 

         if (result == null) { 
          Toast.makeText(getApplicationContext(), 
            "It's null, not working", Toast.LENGTH_LONG) 
            .show(); 
         } 

         if (result != null 
           && result 
             .equals(SERVER_RES_RES_SIGN_UP_SUCCESFULL)) { 
          Toast.makeText(getApplicationContext(), 
            R.string.signup_successfull, 
            Toast.LENGTH_LONG).show(); 
          // showDialog(SIGN_UP_SUCCESSFULL); 
         } else if (result != null 
           && result 
             .equals(SERVER_RES_SIGN_UP_USERNAME_CRASHED)) { 
          Toast.makeText(getApplicationContext(), 
            R.string.signup_username_crashed, 
            Toast.LENGTH_LONG).show(); 
          // showDialog(SIGN_UP_USERNAME_CRASHED); 
         } else // if 
           // (result.equals(SERVER_RES_SIGN_UP_FAILED)) 
         { 
          Toast.makeText(getApplicationContext(), 
            R.string.signup_failed, Toast.LENGTH_LONG) 
            .show(); 
          // showDialog(SIGN_UP_FAILED); 
         } 

        } 

       }); 

      } 
     }; 
     thread.start(); 
    } 

서버 케이스 :

case "createGroup": 

     $SQLtest = "insert into groups(groupName, uniqueGroup, createTime) 
      VALUES('TestGroup', 1234567891, NOW())"; 

      error_log("$SQLtest", 3 , "error_log"); 

     if($result = $db -> query($SQLtest)) 
     { 
      $out = SUCCESSFUL; 
     } 
     else 
     { 
      $out = FAILED; 
     } 

    break; 

메시징 서비스 및이 createGroup 방법 :

public class MessagingService extends Service implements Manager, Updater { 
    // private NotificationManager mNM; 

    public static String USERNAME; 
    public static final String TAKE_MESSAGE = "Take_Message"; 
    public static final String FRIEND_LIST_UPDATED = "Take Friend List"; 
    public static final String MESSAGE_LIST_UPDATED = "Take Message List"; 
    public ConnectivityManager conManager = null; 
    private final int UPDATE_TIME_PERIOD = 15000; 

    private String rawFriendList = new String(); 
    private String rawMessageList = new String(); 

    SocketerInterface socketOperator = new Socketer(this); 

    private final IBinder mBinder = new IMBinder(); 
    private String username; 
    private String password; 
    private boolean authenticatedUser = false; 
    // timer to take the updated data from server 
    private Timer timer; 

    private StorageManipulater localstoragehandler; 

    private NotificationManager mNM; 

    public class IMBinder extends Binder { 
     public Manager getService() { 
      return MessagingService.this; 
     } 

    } 

    @Override 
    public void onCreate() { 
     mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 

     localstoragehandler = new StorageManipulater(this); 
     // Display a notification about us starting. We put an icon in the 
     // status bar. 
     // showNotification(); 
     conManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); 
     new StorageManipulater(this); 

     // Timer is used to take the friendList info every UPDATE_TIME_PERIOD; 
     timer = new Timer(); 

     Thread thread = new Thread() { 
      @Override 
      public void run() { 

       Random random = new Random(); 
       int tryCount = 0; 
       while (socketOperator.startListening(10000 + random 
         .nextInt(20000)) == 0) { 
        tryCount++; 
        if (tryCount > 10) { 
         // if it can't listen a port after trying 10 times, give 
         // up... 
         break; 
        } 

       } 
      } 
     }; 
     thread.start(); 

    } 



    @Override 
    public IBinder onBind(Intent intent) { 
     return mBinder; 
    } 


    @Override 
     public String createNewGroup(String groupName) throws NullPointerException, UnsupportedEncodingException { 
      String params = "action=createGroup"; 

      String result = socketOperator.sendHttpRequest(params); 

      return result; 
     } 
} 

답변

11

코드가 고유의 경쟁 조건이 있기 때문에 . 그리고 사악한. 이런 일에

변경 :로부터는, isConnected를

public ServiceConnection mConnection = new ServiceConnection() { 

     volatile boolean isConnected; 
     public void onServiceConnected(ComponentName className, IBinder service) { 

      isConnected = true; // <--------------------- 

      imService = ((MessagingService.IMBinder) service).getService(); 

      startCommunicationThread(); 
     } 


     public void onServiceDisconnected(ComponentName className) { 

      isConnected = false; // <--------------- 

      imService = null; 
      Toast.makeText(CreateGroup.this, R.string.local_service_stopped, 
        Toast.LENGTH_SHORT).show(); 
     } 
    }; 

그리고 폴링 :

public void onCreate(Bundle savedInstanceState) { 
     bindService(new Intent(CreateGroup.this, MessagingService.class), 
        mConnection, Context.BIND_AUTO_CREATE); 

     // but do not start thread here! 
} 


public ServiceConnection mConnection = new ServiceConnection() { 

     public void onServiceConnected(ComponentName className, IBinder service) { 
      imService = ((MessagingService.IMBinder) service).getService(); 

      startCommunicationThread(); // <----------------------- only here can you start comm. thread 

     } 

     public void onServiceDisconnected(ComponentName className) { 

      imService = null; 
      Toast.makeText(CreateGroup.this, R.string.local_service_stopped, 
        Toast.LENGTH_SHORT).show(); 
     } 
    }; 


void startCommunicationThread() { 
    Thread thread = new Thread() { 
    String result = new String(); 

    @Override 
    public void run() { 
     try { 
      result = imService.createNewGroup(newGroupName); 
      .......... 

} 


당신은 당신의 코드가 더 안전 할 경우, 연결 상태 필드를 사용하여 startCommunicationThread 내에서 갑자기 연결이 끊어지지 않도록하십시오.

+0

감사합니다. – Sauron

0

내 프로젝트에 MessagingService.IMBinder MessagingService에서 가져올 오류가있는 Java 클래스가 있습니까?