2016-05-27 75 views
0

我正在使用Websocket android應用程序。我想用websocket創建註冊和登錄應用程序。我可以通過websocket android project連接到websocket服務器。我使用在線參考創建了註冊,登錄活動。在註冊活動中,當我使用websocketclient Java類的「send」方法將註冊數據存儲到服務器時我得到「java.lang.NullPointerException:試圖調用虛擬方法'void org.java_websocket.client.WebSocketClient.send(java.lang.String)'null對象引用「我的日誌貓窗口上出現錯誤。Android錯誤與Websocket

這裏是我的主要活動:

package org.asperohgedgetws.a7.hgadgetws; 
import android.app.Activity; 
import android.app.Fragment; 
import android.os.Build; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.EditText; 
import android.widget.TextView; 
import org.java_websocket.client.WebSocketClient; 
import org.java_websocket.handshake.ServerHandshake; 
import java.net.URI; 
import java.net.URISyntaxException; 
import android.widget.Button; 
import android.widget.Toast; 
import android.content.Intent; 

public class MainActivity extends Activity implements View.OnClickListener { 
Button bLogout; 
UserLocalStore userLocalStore; 
private WebSocketClient mWebSocketClient; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    bLogout = (Button) findViewById(R.id.bLogout); 
    bLogout.setOnClickListener(this); 
    userLocalStore = new UserLocalStore(this); 
    connectWebSocket(); 
} 
@Override 
protected void onStart() { 
    super.onStart(); 
    if (authenticate()== true){ 
     displayUserDetails(); 
    } else{ 
     Toast.makeText(getApplicationContext(), "Not Registered User :(", Toast.LENGTH_SHORT).show(); 
     startActivity(new Intent(MainActivity.this,Login.class)); 
    } 
} 

private boolean authenticate(){ 
    return userLocalStore.getUserLoggedIn(); 
} 

private void displayUserDetails(){ 
    User user = userLocalStore.getLoggedInUser(); 
} 

@Override 
public void onClick(View v) { 
    switch(v.getId()){ 
     case R.id.bLogout: 
      startActivity(new Intent(this,Login.class)); 
      userLocalStore.clearUserData(); 
      userLocalStore.setUserLoggedIn(false); 
      Toast.makeText(getApplicationContext(), "Logout :)", Toast.LENGTH_SHORT).show(); 
      break; 

    } 
} 

private void connectWebSocket() { 
    URI uri; 
    try { 
     uri = new URI("ws://xxx.xxx.xxx.xxx:xxxx"); 
    } catch (URISyntaxException e) { 
     e.printStackTrace(); 
     return; 
    } 

    mWebSocketClient = new WebSocketClient(uri) { 
     @Override 
     public void onOpen(ServerHandshake serverHandshake) { 
      Log.i("Websocket", "Opened"); 
      //mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL); 
      mWebSocketClient.send("{\"1512BD002\":\"[email protected]\":\"2\"}"); 
     } 

     @Override 
     public void onMessage(String s) { 
      final String message = s; 
      runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 
        //TextView textView = (TextView)findViewById(R.id.messages); 
        //textView.setText(textView.getText() + "\n" + message); 
       } 
      }); 
     } 

     @Override 
     public void onClose(int i, String s, boolean b) { 
      Log.i("Websocket", "Closed " + s); 
     } 

     @Override 
     public void onError(Exception e) { 
      Log.i("Websocket", "Error " + e.getMessage()); 
     } 
    }; 
    mWebSocketClient.connect(); 
} 

public void sendMessage(View view) { 
// EditText editText = (EditText)findViewById(R.id.message); 
    // mWebSocketClient.send(editText.getText().toString()); 
    //editText.setText(""); 
} 
} 

RegisterActivity

package org.asperohgedgetws.a7.hgadgetws; 

import android.content.Intent; 
import android.os.Bundle; 
import android.support.design.widget.FloatingActionButton; 
import android.support.design.widget.Snackbar; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.Toolbar; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Toast; 

import org.java_websocket.handshake.ServerHandshake; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import org.java_websocket.client.WebSocketClient; 

public class Register extends AppCompatActivity implements View.OnClickListener { 

Button bRegister; 
EditText etName, etAge, etUsername, etPassword; 
WebSocketClient nwebsocket; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_register); 

    etName = (EditText) findViewById(R.id.etName); 
    etAge = (EditText) findViewById(R.id.etAge); 
    etUsername = (EditText) findViewById(R.id.etUsername); 
    etPassword = (EditText) findViewById(R.id.etPassword); 
    bRegister = (Button) findViewById(R.id.bRegister); 
    bRegister.setOnClickListener(this); 
} 

@Override 
public void onClick(View v) { 
    switch (v.getId()) { 
     case R.id.bRegister: 
      // Toast.makeText(getApplicationContext(), "Register", Toast.LENGTH_SHORT).show(); 

      String name = etName.getText().toString(); 
      int age = Integer.parseInt(etAge.getText().toString()); 
      String username = etUsername.getText().toString(); 
      String password = etPassword.getText().toString(); 

      User user = new User(name, age, username, password); 
      registerUser(user); 

      break; 
    } 
} 

private void registerUser(User user) { 
    String strtosend = ""; 
    JSONObject object = new JSONObject(); 
    try { 
     // Add the id to the json 
     object.put("name", user.name); 
     object.put("age", user.age); 
     object.put("username", user.username); 
     object.put("password", user.password); 
     strtosend = object.toString(); 

    } catch (JSONException e) { 
     // Handle impossible error 
     e.printStackTrace(); 
    } 
    Toast.makeText(getApplicationContext(), strtosend, Toast.LENGTH_SHORT).show(); 
    nwebsocket.send("Hi!"); 
    Intent loginIntent = new Intent(Register.this, Login.class); 
    startActivity(loginIntent); 
} 
} 

logcat的輸出:

05-27 11:49:54.331 19459-19459/org.asperohgedgetws.a7.hgadgetws  E/AndroidRuntime: FATAL EXCEPTION: main 
                       Process: org.asperohgedgetws.a7.hgadgetws, PID: 19459 
                       java.lang.NullPointerException: Attempt to invoke virtual method 'void org.java_websocket.client.WebSocketClient.send(java.lang.String)' on a null object reference 
                        at org.asperohgedgetws.a7.hgadgetws.Register.registerUser(Register.java:73) 
                        at org.asperohgedgetws.a7.hgadgetws.Register.onClick(Register.java:51) 
                        at android.view.View.performClick(View.java:4780) 
                        at android.view.View$PerformClick.run(View.java:19866) 
                        at android.os.Handler.handleCallback(Handler.java:739) 
                        at android.os.Handler.dispatchMessage(Handler.java:95) 
                        at android.os.Looper.loop(Looper.java:135) 
                        at android.app.ActivityThread.main(ActivityThread.java:5254) 
                        at java.lang.reflect.Method.invoke(Native Method) 
                        at java.lang.reflect.Method.invoke(Method.java:372) 
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 

我必須在註冊活動,下面的代碼再次使用?

private void connectWebSocket() { 
    URI uri; 
    try { 
     uri = new URI("ws://xxx.xxx.xxx.xxx:xxxx"); 
    } catch (URISyntaxException e) { 
     e.printStackTrace(); 
     return; 
    } 

    nWebsocketClient = new WebSocketClient(uri) { 
     @Override 
     public void onOpen(ServerHandshake serverHandshake) { 
      Log.i("Websocket", "Opened"); 
     } 

     @Override 
     public void onMessage(String s) { 
      final String message = s; 
      runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 
       } 
      }); 
     } 

     @Override 
     public void onClose(int i, String s, boolean b) { 
      Log.i("Websocket", "Closed " + s); 
     } 

     @Override 
     public void onError(Exception e) { 
      Log.i("Websocket", "Error " + e.getMessage()); 
     } 
    }; 
    nWebsocketClient.connect(); 
} 
+0

可能重複[什麼是NullPointerException,以及如何解決它?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-doi-i-fix - 我) – 1615903

+0

我得到了什麼是NPE,但在我的情況3我該如何解決它?我在mainActivity中打開websocket連接,如何使用發送功能在已註冊的活動中發送註冊數據。我是Android/Java編碼的新手,所以需要了解。請不要介意。 –

回答

1

的問題是,你的nwebsocket從未初始化,它的價值是null,這就是爲什麼你試圖執行send方法時出現此錯誤。

你需要的地方初始化:

nwebsocket = new WebSocketClient(...); 

注意:如果你想分享MainActivityRegister活動之間的WebSocketClient相同的實例,你可以把它public staticMainActivity

public static WebSocketClient mWebSocketClient; 

然後從Register中刪除WebSocketClient nwebsocket,並使用MainActivity.mWebSocketClient代替。

+0

是的,我明白了你的觀點。在主要活動中,我打開了一個WebSocket連接。現在已註冊的活動爲什麼我應該再次啓動連接?我想通過當前打開的Socket連接發送數據。所以,那就是爲什麼我只想使用發送方法。 –

+0

@Taher查看我的編輯 – fiddler

+0

感謝提琴手,您的編輯答案爲我工作。非常感謝你。通過將其公開化,可以接受其他課程。現在我在主Activity中有一個抽象方法,它從服務器「public void onMessage(String s)」讀入傳入的消息。我需要閱讀此方法的消息,並希望在登錄活動以及註冊活動中使用。 –